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

React-Query MutationCache的onError函数错误类型及TypeScript类型覆写方案

React Query MutationCache onError 错误类型自定义方案

默认错误类型

react-query 的 MutationCache 中,onError 接收的错误默认类型是 unknown。这是因为框架无法预知你的 API 返回的错误结构,所以用最严格的类型确保类型安全。

自定义错误类型的两种方式

1. 全局配置 MutationCache 时指定类型

如果你想让全局所有 mutation 的 onError 都使用自定义错误类型,可以在创建 MutationCache 实例时显式传入泛型参数,其中第二个泛型就是错误类型:

首先定义你的服务器错误类型:

// 定义符合你的 API 错误结构的类型
interface IServerError {
  response: {
    data: {
      fullMessage: string;
    };
  };
  status: number; // 可选,根据实际错误结构添加
}

然后创建带泛型的 MutationCache:

import { MutationCache, QueryClient } from '@tanstack/react-query';

const mutationCache = new MutationCache<unknown, IServerError, unknown, unknown>({
  onError: (error) => {
    // error 已自动推断为 IServerError 类型,无需类型断言
    console.error('服务器错误:', error.response.data.fullMessage);
  },
});

// 将自定义的 mutationCache 传入 QueryClient
const queryClient = new QueryClient({ mutationCache });

2. 单个 mutation 中指定类型

如果只需要给特定的 mutation 自定义错误类型,可以在 useMutation 时传入泛型参数,第二个参数同样代表错误类型:

import { useMutation } from '@tanstack/react-query';

// 假设你的请求参数类型是这样
interface LoginParams {
  username: string;
  password: string;
}

const loginMutation = useMutation<
  // 第一个泛型:请求成功返回的数据类型
  { token: string },
  // 第二个泛型:自定义错误类型
  IServerError,
  // 第三个泛型:请求参数类型
  LoginParams
>({
  mutationFn: (params) => {
    return fetch('/api/login', {
      method: 'POST',
      body: JSON.stringify(params),
    }).then(res => res.json());
  },
  onError: (error) => {
    // 直接使用 error.response.data.fullMessage,无需断言
    alert('登录失败: ' + error.response.data.fullMessage);
  },
});

处理多种错误场景

如果你的应用中存在多种错误类型(比如网络错误、服务器错误),可以用联合类型 + 类型守卫来处理:

// 扩展错误类型
type AppError = IServerError | NetworkError;

interface NetworkError {
  type: 'network';
  message: string;
}

// 在 onError 中区分处理
onError: (error: AppError) => {
  if ('response' in error) {
    // 这里 error 被推断为 IServerError
    console.error(error.response.data.fullMessage);
  } else if (error.type === 'network') {
    // 这里 error 被推断为 NetworkError
    console.error('网络错误:', error.message);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:35:19