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

Fetch Promise已Resolve但Redux Saga后续代码不执行求助

排查Redux Saga中yield call后代码不执行的问题

嘿,我来帮你搞定这个问题!你遇到的情况是yield call(request, ...)之后的代码完全没执行,大概率是Promise链中存在未被捕获的错误,导致Redux Saga的generator直接终止了。咱们一步步来排查:

1. 先给Saga加上错误捕获

你的loadData函数里只有try块,没有catch块。如果request返回的Promise抛出错误,Saga会直接终止这个generator,根本不会走到call之后的代码。先补上catch块看看具体错误:

export function* loadData() {
  console.log("Saga: Loading Data...");
  try {
    const response = yield call(request, requestURL, {
      method: 'GET',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
      }
    });
    // 现在看看能不能走到这里
    console.log("拿到响应了:", response);
    if (response.success) {
      console.log("SUCCESS!!!!");
      // ...你的其他逻辑
    }
  } catch (error) {
    // 这里会打印出具体的错误原因
    console.error("Saga请求出错啦:", error);
    console.error("错误详情:", error.stack);
  }
}

2. 检查parseJSON函数是否有问题

你说checkStatus已经确认请求成功,但parseJSON环节很容易出问题——比如服务器返回的响应体不是合法的JSON,或者是空的,这时候response.json()会抛出错误,导致Promise reject。

可以给parseJSON加个错误处理:

function parseJSON(response) {
  try {
    return response.json();
  } catch (e) {
    console.warn("解析JSON失败,返回默认对象:", e);
    return {}; // 返回空对象,避免Promise reject
  }
}

3. 确认checkStatus的逻辑是否严谨

有时候一些特殊状态码(比如304缓存)可能被你的checkStatus误判为错误。调整一下逻辑,覆盖更多合法的成功状态:

function checkStatus(response) {
  // 2xx系列 + 304(未修改)都算成功
  if ((response.status >= 200 && response.status < 300) || response.status === 304) {
    return response;
  } else {
    const error = new Error(response.statusText);
    error.response = response;
    throw error;
  }
}

4. 给request函数加全局错误日志

在request的Promise链最后加个catch,方便定位错误发生在哪个环节:

export default function request(url, options) {
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .catch(error => {
      console.error("Request函数内部出错:", error);
      throw error; // 重新抛出错误,让Saga的catch捕获
    });
}

按照上面的步骤排查,你应该能很快找到问题所在——大概率是JSON解析失败或者某个隐藏的错误导致Promise没有正常resolve,进而让Saga的generator终止了。

内容的提问来源于stack exchange,提问作者Manuel Escalante

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:16:37