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

SWR错误返回至data对象而非error对象,无法捕获问题求助

问题原因分析

SWR 的 error 始终为 undefined 的核心原因是:你的 SWR 请求使用的 fetcher 函数没有在接收到 422 这类非 2xx 状态码时抛出异常。

SWR 只会在 fetcher 函数抛出异常时,才会将异常赋值给 error 变量。如果 fetcher 只是返回了错误状态的响应体,SWR 会将其视为正常响应,存入 data 中,而非 error。

具体到你的场景:

  1. 后端返回 422 错误后,getData 函数抛出了错误数据
  2. /api/form 路由捕获该错误,返回 422 状态码和错误 JSON
  3. 前端 SWR 的 fetcher 接收到这个 422 响应,但没有抛出异常,导致 SWR 将错误数据存入 data,error 保持 undefined

另外,如果你使用的是 SWR 默认的 fetcher,它仅支持 GET 请求,无法正确处理你传入的 POST 配置(method: 'POST'、body 等),这也可能导致请求行为不符合预期。

解决方案

实现一个自定义 fetcher 函数,让它:

  1. 正确处理 POST 请求的配置
  2. 检查响应状态,若 response.ok 为 false(即状态码不在 200-299 范围内),则解析错误响应体并抛出异常

自定义 Fetcher 代码

const customFetcher = async (url, options) => {
  const response = await fetch(url, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
  });

  // 非2xx状态码时抛出错误
  if (!response.ok) {
    const errorData = await response.json();
    throw errorData;
  }

  return response.json();
};

更新 useSWR 调用

将自定义 fetcher 作为第二个参数传入 useSWR:

const { data, error, isValidating } = useSWR(
  conditionMet
    ? [
        '/api/form',
        {
          method: 'POST',
          body: JSON.stringify({
            // 你的请求数据
          }),
        },
      ]
    : null,
  customFetcher, // 传入自定义fetcher
  {
    revalidateIfStale: false,
    revalidateOnFocus: false,
    revalidateOnReconnect: false,
    revalidateOnMount: true,
    suspense: true,
    keepPreviousData: true,
  }
);

这样,当 /api/form 返回 422 状态码时,customFetcher 会抛出错误数据,SWR 会将其赋值给 error 变量,你就能正常捕获到错误了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 11:31:02