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

React TS中RTK Query展示API错误时的类型警告解决方法

解决RTK Query中React TypeScript的错误类型警告问题

RTK Query返回的error类型是FetchBaseQueryError | SerializedError联合类型:

  • FetchBaseQueryError对应API返回的业务错误,包含data属性
  • SerializedError对应网络错误、请求中断这类系统错误,没有data属性

TypeScript报错就是因为无法确定当前error属于哪一种类型,下面是几种可行的解决方案:

方案一:使用类型守卫(推荐,类型安全)

写一个类型守卫函数,帮TypeScript识别错误类型:

import { FetchBaseQueryError } from '@reduxjs/toolkit/query/react';

function isFetchBaseQueryError(error: unknown): error is FetchBaseQueryError {
  return typeof error === 'object' && error !== null && 'data' in error;
}

然后在组件中使用:

const [login, { isLoading, isError, error }] = useLoginMutation();

return (
  <div>
    {isError && (
      <div className="bg-neRed-200 text-neRed-900 font-medium py-1 px-2 text-sm rounded">
        {isFetchBaseQueryError(error) ? error.data?.error : '请求失败,请稍后重试'}
      </div>
    )}
  </div>
);

方案二:类型断言(适合明确错误来源的场景)

如果能确定当前错误是API返回的业务错误,可以直接用类型断言,但要配合可选链保证安全:

{isError && ((error as FetchBaseQueryError).data?.error || '请求出错')}

方案三:在Mutation定义时指定错误类型

如果你的API错误响应格式固定,可以在定义mutation时通过transformErrorResponse指定错误类型:

import { build.mutation } from '@reduxjs/toolkit/query/react';

// 定义你的API错误格式
interface ApiErrorResponse {
  error: string;
}

const loginMutation = build.mutation<LoginResponse, LoginParams>({
  query: (credentials) => ({
    url: '/login',
    method: 'POST',
    body: credentials,
  }),
  transformErrorResponse: (response: { data: ApiErrorResponse }) => response.data,
});

这样useLoginMutation返回的error类型会变成ApiErrorResponse | SerializedError,处理时更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 04:02:16