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

React项目使用Axios请求接口时无法向用户展示错误提示

问题根因

错误信息无法渲染到页面是代码中4处逻辑错误导致的:

  • catch回调中状态赋值错误:你写的是setError(typeof (error.message)),typeof只会返回值的类型字符串(此处固定返回"string"),根本没有把实际错误内容存入状态。
  • 状态初始值类型不匹配:error的初始值是空字符串"",渲染时你读取error.message,字符串类型不存在message属性,该值永远为undefined,错误提示的判断条件永远无法成立。
  • 错误判断逻辑硬编码:你只匹配了状态码404的固定错误文本,遇到网络超时、500服务端错误等其他异常时,就算错误值正确也不会展示提示。
  • 缺少状态重置逻辑:切换用户id发起新请求时,没有清空上一次请求留存的错误、用户数据状态,容易出现内容渲染错乱。
修复方案
  1. 修正catch块的状态赋值逻辑,直接存储捕获到的错误对象
  2. 调整error状态初始值为null,方便判断是否存在请求异常
  3. 调整渲染判断顺序:优先判断错误状态,再判断加载状态,最后渲染正常用户信息,移除硬编码的错误文本匹配
  4. 每次id变化发起新请求前,重置所有相关状态,避免旧数据残留

修复后的完整代码如下:

import { useParams, Link } from 'react-router-dom';
import { useState, useEffect } from 'react';
import axios from 'axios';

function User() {
    const { id } = useParams();
    const [user, setUser] = useState(null);
    const [error, setError] = useState(null);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        // 发起新请求前重置所有状态
        setError(null);
        setIsLoading(true);
        setUser(null);

        axios(`https://jsonplaceholder.typicode.com/users/${id}`)
            .then(res => setUser(res.data))
            .catch(err => {
                // 直接存储错误对象到状态
                setError(err);
            })
            .finally(() => {
                setIsLoading(false);
            });
    }, [id]);

    return (
        <div>
            {error ? (
                <p style={{ color: 'red' }}>请求异常:{error.message}</p>
            ) : isLoading ? (
                <h2>Loading...</h2>
            ) : user ? (
                <div>
                    <h3>User Info</h3>
                    <p>Name: {user.name}</p>
                    <p>Email: {user.email}</p>
                    <p>Phone: {user.phone}</p>
                </div>
            ) : null}
            <Link to={`/users/${parseInt(id) + 1}`}><button>Next User</button></Link>
        </div>
    )
}

export default User
补充说明

你之前在控制台打印error.message == 'Request failed with status code 404'能得到true,是因为catch块中拿到的原始错误对象确实携带正确的message属性,但你存入状态的是typeof返回的类型字符串,渲染时读取的是状态中的错误值,自然无法获取到正确的提示内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 02:39:09