对“这个"的引用在 redux-saga 调用的函数中为 null [英] Reference to "this" is null in function called by redux-saga call
问题描述
我正在学习 redux-saga
,我正在尝试将它集成到一个项目中,该项目使用由 openapi-generator 生成的 API,该 API 产生如下输出:
I'm learning redux-saga
and I'm trying to integrate it into a project that uses an API that is generated with openapi-generator which produces output like the following:
async loginUser(body: Login): Promise<LoginResponse> {
debugger;
const response = await this.loginUserRaw({ body: body });
return await response.value();
}
而 loginUserRaw
是一个执行实际登录的函数.然后,我有以下传奇:
And loginUserRaw
is a function that performs the actual login. Then, I have the following saga:
function* login(action:Login) {
try{
const response = yield call(User.loginUser, action);
yield result(LOGIN_SUCCESS, response)
}catch(e){
yield result(LOGIN_FAILURE, e)
}
}
运行时,我的 API 方法的 await this.loginUserRaw({ body: body });
行中出现错误:
When this runs, I get an error in my API method's await this.loginUserRaw({ body: body });
line:
TypeError: 无法读取 null 的属性 'loginUserRaw'
我调试它并看到 this
为空.当我在 saga 中显式绑定函数时:
I debug it and see that this
is null. When I bind the function explicitly in the saga:
const response = yield call(User.loginUser.bind(User), action);
它有效,但我不想每次调用函数时都绑定它.如何在不显式绑定函数的情况下让 saga 工作?(我也无法更改生成的代码并删除 this
)
It works, but I don't wanna bind it every time I call a function. How can I get saga to work without explicitly binding the function? (I can't change the generated code and remove this
either)
推荐答案
Javascript 中的上下文是动态的,基于您编写代码的方式
Context in Javascript is dynamic based on the way you've written your code
const loginUser = User.loginUser
loginUser() // context lost, because there is no longer `User.` in front of it
同样适用于将函数作为参数传递的情况.这意味着您必须以某种方式提供 call
效果上下文.bind
方法是一种选择,但是效果本身支持多种提供上下文的方式.您可以在官方文档 https://redux-saga 中找到它们.js.org/docs/api/#callcontext-fn-args,这是它的简短版本:
Same applies when you pass a function as an parameter. This means that you have to provide the call
effect context in some way. The bind
method is one option, however the effect itself supports multiple ways of providing context. You can find them in the official docs https://redux-saga.js.org/docs/api/#callcontext-fn-args, here is the short version of it:
传递上下文的可能方法:
Possible ways to pass context:
call([context, fn], ...args)
call([context, fnName], ...args)
call({context, fn}, ...args)
例如,您可以执行以下操作:
So for example you can do the following:
const response = yield call([User, User.loginUser], action);
这篇关于对“这个"的引用在 redux-saga 调用的函数中为 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!