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

React中使用Axios请求时错误信息无法清除的解决方法

问题根源

两个异常现象的核心原因是状态重置时机错误:

  • 若将setError("")写在finally代码块中,无论请求成功或失败都会执行错误清空逻辑,catch块中刚写入的错误信息会被直接覆盖,导致错误提示完全失效
  • 若不在新请求发起前重置状态,上一次请求留存的error、user数据会残留,就会出现切换到有效用户ID后旧错误信息不消失、无法正常展示用户详情的问题
修复方案

正确的处理逻辑是:每次路由参数id变化、触发新请求前,先将所有相关状态重置为初始加载态,finally块仅负责关闭加载状态,不处理错误清空逻辑。
修复后的完整代码如下:

import { useParams } 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("");
  const [isLoading, setIsLoading] = useState(true);

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

    axios("https://jsonplaceholder.typicode.com/users/" + id)
      .then((res) => setUser(res.data))
      .catch((error) => setError(error.message))
      .finally(() => setIsLoading(false));
  }, [id]);

  return (
    <div>
      {error ? (
        <p>请求错误:{error}</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}
    </div>
  );
}

export default User;
改动说明
  • 状态重置逻辑前移到请求发起前:只要id变化触发重新请求,第一时间清空上一次留存的错误信息、旧用户数据,同时开启加载状态,从根源避免旧内容残留
  • 移除finally块中的错误清空逻辑:catch中写入的错误信息不会被后续流程覆盖,404、网络连接异常等场景的错误提示都可以正常展示
  • 优化渲染判断逻辑:不再硬编码只匹配404的错误文案,所有接口、网络错误都能正常提示;增加user存在性校验,避免请求未完成时访问user.name触发空值报错

内容的提问来源于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:57:14