SWR错误返回至data对象而非error对象,无法捕获问题求助
问题原因分析
SWR 的 error 始终为 undefined 的核心原因是:你的 SWR 请求使用的 fetcher 函数没有在接收到 422 这类非 2xx 状态码时抛出异常。
SWR 只会在 fetcher 函数抛出异常时,才会将异常赋值给 error 变量。如果 fetcher 只是返回了错误状态的响应体,SWR 会将其视为正常响应,存入 data 中,而非 error。
具体到你的场景:
- 后端返回 422 错误后,
getData函数抛出了错误数据 /api/form路由捕获该错误,返回422状态码和错误 JSON- 前端 SWR 的 fetcher 接收到这个 422 响应,但没有抛出异常,导致 SWR 将错误数据存入
data,error保持undefined
另外,如果你使用的是 SWR 默认的 fetcher,它仅支持 GET 请求,无法正确处理你传入的 POST 配置(method: 'POST'、body 等),这也可能导致请求行为不符合预期。
解决方案
实现一个自定义 fetcher 函数,让它:
- 正确处理 POST 请求的配置
- 检查响应状态,若
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
相关产品推荐
相关产品推荐

