为什么 yield call(response.json) 挂起?

问题描述

const response = yield call(fetch,`${config.backendUrl}/verify`,{
  method: 'POST'
})

const responseJson = yield call(response.json)

console.log(responseJson)

这是来自 redux-saga 的代码。 Yield 挂起,console.log 不打印任何内容。但是,如果我用 response.json 替换 () => response.json(),它会起作用。为什么?

解决方法

那是因为当您调用 yield call(response.json) 时,会使用错误的上下文 (response.json) 调用 this

您可以使用 bind(例如 yield call(response.json.bind(response)))或通过指定 context(例如 yield call([response,response.json]))来解决此问题,但是 call 在这里真的没用。你可以:

const responseJson = yield response.json();