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

使用fetch发送邮件的API返回undefined且报读取json错误,但邮件发送成功

问题分析与解决

核心错误原因

你的timeout函数没有返回Promise对象,导致Promise.race([request, timeout()])行为异常:

  • 当请求超时触发时,timeout()实际返回undefined,Promise.race进入reject状态,但后续代码仍尝试访问response.json(),此时response为undefined,直接抛出"Cannot read properties of undefined (reading 'json')"错误。
  • 之前测试正常是因为请求都在5秒内完成,超时逻辑未触发,bug被隐藏;现在请求响应变慢或超时,才暴露问题。

修复步骤

1. 修复timeout函数,添加返回值

修改fetchData.js里的timeout函数,确保返回Promise实例:

const timeout = () => {
  // 关键:加上return返回Promise
  return new Promise((_, reject) => {
    setTimeout(
      () => reject(Error("Something went wrong, please try again")),
      5000
    );
  });
};

2. 增加安全校验(可选)

在处理response前先判断其是否存在,避免同类错误再次发生:

export const useFetch = async (url, emailData) => {
  try {
    const request = fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(emailData),
    });
                
    const response = await Promise.race([request, timeout()]);

    // 新增:检查response是否存在
    if (!response) {
      throw Error("Request timed out or failed to get response");
    }
        
    const data = await response.json();

    if (!response.ok) throw Error(data.message);
    
    return data;
  } catch (error) {
    if (error.message === "Failed to fetch")
      error.message = `Unable to reach the server. Please check your internet connection...`;
    throw error;
  }
};

额外说明

邮件能成功发送是因为服务器已接收并处理请求,但前端因超时逻辑的bug未正确处理响应,导致抛出错误。修复后,超时场景会正确进入catch分支返回对应错误提示,而非抛出undefined异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 20:24:51