redux-saga 调用调用的函数中对 "this" 的引用为空

Reference to "this" is null in function called by redux-saga call

我正在学习 redux-saga,我正在尝试将它集成到一个项目中,该项目使用一个 API,该项目由 openapi-generator 生成,生成如下所示的输出:

async loginUser(body: Login): Promise<LoginResponse> {
    debugger;
    const response = await this.loginUserRaw({ body: body });
    return await response.value();
}

loginUserRaw是一个执行实际登录的函数。然后,我有以下传奇:

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 }); 行出现错误:

TypeError: Cannot read property 'loginUserRaw' of null

我调试它,发现 this 为空。当我在 saga 中显式绑定函数时:

const response = yield call(User.loginUser.bind(User), action);

它可以工作,但我不想每次调用函数时都绑定它。如何在不显式绑定函数的情况下让 saga 工作? (我无法更改生成的代码并删除 this

Javascript 中的上下文是动态的,具体取决于您编写代码的方式

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,这里是它的简短版本:

传递上下文的可能方法:

call([context, fn], ...args)
call([context, fnName], ...args)
call({context, fn}, ...args)

例如,您可以执行以下操作:

const response = yield call([User, User.loginUser], action);