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

React中处理Promise:修复API接口JSON数据获取报错问题

修复React Fetch API获取JSON数据的错误

问题背景

本地localhost:8000端口有一个API接口,返回固定JSON对象{"message": "hello"}。使用以下React代码请求时,控制台显示Data fetched correctly!,但随即抛出错误:Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern.。

原错误代码:

import React, {useEffect, useState} from "react";

const App = () => {
    const [message, setMessage] = useState("");
    const getHomePageData = async () => {
        const requestOptions = {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
            },
        };
        const response = await fetch("/", requestOptions)
        if (!response.ok) {
            console.log("Error in fetching the data!");
        } else {
            console.log("Data fetched correctly!");
        }
        return await response.json();
    };
    const data = getHomePageData();
    console.log(data);
    return(
        <center><h1>Hello, world!</h1></center>
    );
}
export default App;

错误原因

  1. 异步函数未正确挂载执行:直接在组件顶层调用getHomePageData(),会返回未处理的Promise,组件渲染时同步执行异步逻辑,导致Promise未被await处理,触发未捕获的拒绝。
  2. 错误响应仍强制解析JSON:即使response.ok为false(如4xx/5xx状态码),代码仍执行response.json(),若错误返回的不是JSON格式内容,就会抛出解析错误。
  3. 缺少全局异常捕获:整个异步请求流程未用try/catch包裹,无法捕获网络错误或JSON解析错误。

修复方案

  1. 将请求逻辑放入useEffect钩子,确保组件挂载后执行异步操作。
  2. 用try/catch包裹整个请求流程,捕获所有可能的异常。
  3. 仅在response.ok为true时解析JSON,错误分支直接处理错误信息。
  4. 用await获取异步结果,更新组件state展示数据。

修复后的完整代码

import React, { useEffect, useState } from "react";

const App = () => {
    const [message, setMessage] = useState("");

    const getHomePageData = async () => {
        const requestOptions = {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
            },
        };
        try {
            // 注意:若React开发服务器端口不是8000,需写完整API地址,或配置proxy
            const response = await fetch("http://localhost:8000/", requestOptions);
            if (!response.ok) {
                throw new Error(`请求失败:${response.status}`);
            }
            console.log("Data fetched correctly!");
            const data = await response.json();
            setMessage(data.message);
        } catch (error) {
            console.error("获取数据出错:", error);
        }
    };

    // 组件挂载时执行请求
    useEffect(() => {
        getHomePageData();
    }, []);

    return (
        <center>
            <h1>{message || "Hello, world!"}</h1>
        </center>
    );
};

export default App;

额外说明

如果React项目的开发服务器端口和后端API端口不同,直接用"/"会请求React开发服务器的根路径,而非后端API。可以选择:

  • 写完整的API地址"http://localhost:8000/"
  • 在React项目的package.json中添加"proxy": "http://localhost:8000",之后就能直接用"/"请求后端接口

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:40:48