【问题标题】:Cannot call `call` because: Either property `context` is missing in function flow error when using Redux-Saga?无法调用`call`,因为:使用Redux-Saga时函数流错误中缺少属性`context`?
【发布时间】:2021-10-26 20:55:15
【问题描述】:

我有一段代码正在使用来自 redux saga 的 yield call api,它正在调用一个函数并提供一个输入。

它正在调用一个简单的 POST 函数,该函数在点击 api 时返回响应。

此函数的输入是一个名为code 的字符串,它是通过url 中的参数设置的。我们使用URLSearchParams 根据关键字从 URL 中获取特定参数。

问题的根源似乎在于此 URLSearchParams 使用窗口对象来获取代码。这导致 yield 调用出现问题并给我以下 Flow 错误:

无法调用call,因为:其中一个属性context 缺失 函数 1 但存在于对象类型 [2] 中。或属性context 是 在函数 1 中缺失,但存在于对象类型 [3] 中。或财产 函数中缺少context

代码如下:

const params = new URLSearchParams(window.location.search);
const code = params.get('code');
const res = yield call(confirmCode, code); // This call is where the error is happening

这是它正在调用的 confirmCode 函数:

export function confirmCode(code: string): Promise<TResp<void>> {
  return request(`/agent/v1/confirm-code/${code}`, {
    method: 'POST',
    mode: 'cors',
  });
}

【问题讨论】:

    标签: javascript flowtype redux-saga yield


    【解决方案1】:

    params.get('code'); 返回null | string 所以实际上你的问题是code 传递给callconfirmCode 不兼容。

    您可以从函数定义中通过两种方式解决此问题,这意味着您可能希望向代码添加默认值

    export function confirmCode(code: ?string): Promise<TResp<void>> {
      return request(`/agent/v1/confirm-code/${code}`, {
        method: 'POST',
        mode: 'cors',
      });
    }
    

    或者在运行call之前检查code是否有效

    const params = new URLSearchParams(window.location.search);
    const code = params.get('code');
    if (code) {
      const res = yield call(confirmCode, code);
    }
    

    【讨论】:

    • 太好了,谢谢。我选择了后一种解决方案,感谢您的解释。
    猜你喜欢
    • 1970-01-01
    • 2019-07-15
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    相关资源
    最近更新 更多