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

React useAsync无法接收fetchData返回数据的问题求助

问题分析与解决

核心问题:重复调用res.json()

你代码里的console.log(res.json());和return res.json();是导致data为undefined的直接原因。因为res.json()会一次性消费响应体流,第一次调用后,响应体已经被读取完毕,第二次调用res.json()会返回一个状态为resolved但值为undefined的Promise,所以useAsync最终拿到的data就是undefined。

另外,console.log(res.json())打印的其实是一个Promise对象,你能看到数据是因为浏览器控制台会展开Promise的resolved值,但这并不代表它同步返回了数据。

修复代码

把res.json()的结果存储到变量中,再复用这个变量:

const fetchData = async () => {
    const apiUrl = "http://localhost:8080/user/natt@gmail.com";
    const requestOptions = {
        method: "GET",
        headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
            "Content-Type": "application/json",
        },
    };
   
    const res = await fetch(apiUrl, requestOptions);
    if (!res.ok) throw new Error(res.statusText);
    // 只调用一次res.json(),存储结果
    const responseData = await res.json();
    console.log(responseData); // 这里打印实际数据
    return responseData;
}

const { data, error, isLoading } = useAsync({ promiseFn: fetchData });
console.log(data);
if (isLoading) return <Grid>"Loading..."</Grid>;
if (error) return <Grid>Something went wrong: {`${error.message}`}</Grid>;
if (data) return(<Grid>"main code"</Grid>)

额外注意点

  • 函数名拼写:你写的fecthData是拼写错误,应该是fetchData(规范起见建议修正)。
  • 确认useAsync的参数格式:如果使用的是react-use库的useAsync,正确用法应为const { data, error, isLoading } = useAsync(fetchData);,无需包裹成{ promiseFn: fetchData },需要根据你使用的具体库调整参数格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:05:42