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

React useEffect调用getToken接口打印正常却无返回值问题

问题原因及修复方案

1. 不符合规范的useEffect异步写法

useEffect不支持直接传入async函数作为参数,因为async函数默认返回Promise,而React要求useEffect的返回值必须是清理函数,这会导致内部逻辑执行异常,是你logger.log('returned')始终无法输出的核心原因。
正确的异步调用写法:

useEffect(() => {
  const fetchToken = async () => {
    try {
      const result  = await getToken(urlSuffix);
      logger.log('returned')
      setToken(result);
    } catch (error) {
      logger.debug('ERROR: ', error);
    }
  }
  fetchToken();
}, [urlSuffix]);

2. fetch响应未正确解析(如果使用原生fetch)

如果你用的是原生fetch而非封装后的请求库,await fetch()返回的是Response对象,没有data属性,需要先调用.json()解析响应体才能拿到业务数据:

export const getToken = async (urlSuffix) => {
  try {
    const url = `https://api_url/api/v1/asset/${urlSuffix}`;
    const response = await fetch(url, {
      headers: {
        'Accept': 'application/json',
        'X-Api-Key': API_KEY,
      },
      method: 'get',
    });
    // 新增这行解析响应体
    const data = await response.json();
    const token = data?.data?.collection?.token;
    logger.debug('TOKEN: ', token);
    return token;
  } catch (error) {
    logger.debug('TOKEN FETCH ERROR');
    // 抛出错误方便上层捕获,避免静默失败
    throw error;
  }
};

注:原生fetch不支持timeout配置,你写的timeout参数不会生效,需要自己封装超时逻辑。

3. 异常被静默吞掉

getToken的catch块只打印了日志没有抛出错误,即使内部逻辑出错也不会触发上层的catch分支,只会返回undefined,补充throw error即可让上层捕获到异常。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:24:10