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

React中useEffect内async/await调用为何处于pending状态?

React useEffect异步调用获取文本内容的解决方案

你碰到的问题核心是:response.text()本身是异步方法,返回的是Promise对象——哪怕你已经通过await fetch(...)拿到了响应对象,直接打印它依然会输出Promise,而不是解析后的实际文本。

方案一:用await二次等待文本解析

修改代码,对response.text()也使用await,确保等待它完成解析:

useEffect(() => {
  async function fetchConstitution() {
    const response = await fetch(constitution_text);
    const text = await response.text(); // 这里加上await获取实际文本
    console.log(text);
    return response;
  } 

  fetchConstitution();
}, []);

方案二:用.then()链式处理Promise

如果用.then()重构,需要在response.text()后追加链式调用,才能拿到实际文本:

useEffect(() => {
  fetch(constitution_text)
    .then(response => response.text())
    .then(text => console.log(text));
}, []);

补充说明:await和.then()的作用本质是一致的,都是处理异步Promise的手段——await只是同步风格的语法糖,底层还是基于Promise实现的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 12:07:13