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

使用useAsync时函数返回数据为何显示undefined?

问题原因及解决方案

你的代码里data初始为undefined、状态一直pending,主要有以下几种可能:

1. 初始渲染阶段异步请求未完成

组件第一次渲染时,useAsync还没完成异步请求,此时isLoading为true,data自然是undefined。你直接在组件顶层打印data,只会捕获到初始状态的值,等请求完成后组件会重新渲染,这时候data才会有值。

2. 异步函数内部出错

如果axios.get请求失败(比如URL错误、网络问题),或者current(req)处理数据时抛出异常,会导致weatherData返回的promise被拒绝。此时useAsync的error会包含错误信息,但data仍为undefined,isLoading会变为false。你没处理错误状态,可能没察觉到请求失败。

3. react-async配置或版本问题

虽然你传了promiseFn,但如果使用的react-async版本较旧,或者存在配置遗漏(比如默认autoRun被禁用),也会导致请求不触发。不过默认情况下useAsync会自动执行promiseFn,这个概率较低。


解决步骤:

  • 正确处理状态分支:在组件里根据isLoading和error渲染对应内容,避免在初始阶段依赖data:

    const WeatherList = () => {
      const { data, error, isLoading } = useAsync({
        promiseFn: weatherData,
      });
    
      if (isLoading) return <div>加载中...</div>;
      if (error) return <div>请求出错:{error.message}</div>;
      // 此时data已存在,可以正常使用
      console.log(data);
      return <div>{/* 渲染数据 */}</div>;
    };
    
  • 排查异步函数正确性:单独测试weatherData函数,确认getURLs(...getTime()).curr生成的URL有效,axios.get能拿到正确响应,current(req)处理后的数据符合预期。可以在weatherData里添加错误捕获:

    const weatherData = async () => {
      try {
        let req = await axios.get(getURLs(...getTime()).curr);
        let reqData = current(req);
        return reqData;
      } catch (err) {
        console.error('请求或数据处理出错:', err);
        throw err; // 抛出错误让useAsync捕获
      }
    };
    
  • 确认react-async版本:确保使用的是最新稳定版,确认useAsync的参数用法符合当前版本要求。

内容的提问来源于stack exchange,提问作者최석규

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 05:45:31