You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Saga调用API函数有返回值但无法接收问题求助

问题:Redux Saga调用异步API后无法获取返回值,后续代码不执行

我在Saga文件中编写了生成器函数timeTableRequest,用于调用API从数据库获取信息,并添加了console.log作为调试断点。API模块中的requestTimetable异步函数执行GET请求后,能在控制台打印出获取到的requestedTimetable,但返回值无法传递回Saga函数,导致Saga中checkpoint-N2及后续代码无法正常执行。

相关代码

Saga文件中的timeTableRequest函数

function* timeTableRequest(action) {
  try {
    console.log("checkpoint-N1")
    const timetable = yield call(API.requestTimetable(action.id));
    console.log("checkpoint-N2");
    console.log("timetable", timetable);
    yield put(timeTableRequestSuccess(timetable));
  }
  catch (error) { yield put(timeTableRequestError(error)) }
}

API模块中的requestTimetable函数

export const requestTimetable = async (id) => {
  const response = await fetch("https://xxx.xxxxxxx.com/admin/shop/" + localStorage.getItem("shop-id") + "/timetable/" + id + "/slot", {
    method: "GET",
    headers: { "Authorization": `Bearer ${JSON.parse(APIauth.getItem())}` }
  });
  if (!response.ok) { const errorResponse = await response.json(); throw new Error(errorResponse.message) }
  const requestedTimetable = await response.json();
  console.log("requestedTimetable", requestedTimetable)
  return requestedTimetable;
};

控制台日志截图

控制台日志截图


解决方案

问题出在Redux Saga的call函数用法上:你直接执行了API.requestTimetable(action.id),将异步函数返回的Promise传给了call,但call的正确用法是传入函数本身,再依次传入函数所需的参数。

修改Saga中的调用代码:

// 原错误写法
// const timetable = yield call(API.requestTimetable(action.id));

// 修改后正确写法
const timetable = yield call(API.requestTimetable, action.id);

原因说明

Redux Saga的call函数需要接收函数引用和参数,它会帮你执行这个异步函数并等待其完成。如果直接执行函数,会立刻返回Promise,Saga无法正确追踪这个Promise的状态,导致代码卡在yield call这一步,后续的checkpoint-N2等代码自然不会执行。


内容的提问来源于stack exchange,提问作者Miquel Bars

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 22:45:14