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

使用Axios与SWR的React应用遇404等错误码崩溃如何解决

问题根本原因

你在SWRConfig全局配置中开启了suspense: true,该模式下SWR的行为和默认模式有差异:请求出错时不会将错误赋值给useSWR返回的error字段,而是直接向上抛出未捕获的异常,因此你在MyComponent中写的if (error)判断逻辑完全不会生效,未捕获的异常自然会导致应用崩溃。

两种解决方案

方案1:关闭Suspense模式(最简单适配现有代码)

直接修改App.jsx中的SWR全局配置,删除suspense: true配置项即可:

// App.jsx SWRConfig 部分修改后
<SWRConfig
  value={{
    fetcher: (url) => axiosConfig.get(url),
    dedupingInterval: 10000,
    shouldRetryOnError: false,
    revalidateOnFocus: false,
    // 删掉suspense: true这一行
  }}
>

修改后你MyComponent里的错误判断逻辑就会正常生效,接口返回错误码时会直接展示你写的错误提示。

方案2:保留Suspense模式,新增错误边界(ErrorBoundary)捕获异常

如果你需要继续使用Suspense的懒加载、请求等待统一处理能力,就需要搭配React的错误边界组件来捕获SWR抛出的异常:

  1. 首先新建ErrorBoundary.jsx组件:
import React from 'react';

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  componentDidCatch(error, errorInfo) {
    // 这里可以加错误上报逻辑
    console.error("请求出错:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // 自定义错误提示UI
      return <div>Something went wrong!</div>
    }
    return this.props.children;
  }
}

export default ErrorBoundary;
  1. 修改App.jsx,用ErrorBoundary包裹Suspense区域:
import ErrorBoundary from './ErrorBoundary'

// 其他代码不变
return (
  <SWRConfig
    value={{
      fetcher: (url) => axiosConfig.get(url),
      dedupingInterval: 10000,
      shouldRetryOnError: false,
      revalidateOnFocus: false,
      suspense: true
    }}
  >  
    <main className="container">      
      <ErrorBoundary> {/* 新增错误边界包裹 */}
        <Suspense fallback={<Loading />}>
          <Routes>
            <Route element={<MyComponent/>} {...props} />
            // etc...
          </Routes>        
        </Suspense>
      </ErrorBoundary>
    </main>  
  </SWRConfig>  
)

这样SWR抛出的请求错误会被ErrorBoundary捕获,不会导致整个应用崩溃,也可以自定义错误展示样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:27:02