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

React-Query中API函数的TypeScript类型错误求助

解决React-Query useMutation的TypeScript类型错误

问题复现

以下是触发类型错误的React-Query代码:

import {useMutation, useQueryClient} from 'react-query';
import axios from 'axios';

interface userInterface {
 email: string;
 password: string;
}


const loginUser = (user:userInterface) => {
   return axios.post('http://127.0.0.0/login',user);
};

export const useLoginApi = () => {
  interface BodyInterface {
     email: string;
     password: string;
  }

  interface ErrorInterface {
    status: string;
  }

  const {
    mutate: loginUserMutator,
    isError,
    error,
  } = useMutation<BodyInterface, ErrorInterface>(loginUser);

  return {
    loginUserMutator,
    isError,
    error,
  };
};

调用useMutation传入loginUser时触发TypeScript错误:

无匹配的重载调用。最后一个重载给出以下错误:类型为'() => Promise<AxiosResponse<any, any>>'的参数无法赋值给类型'MutationKey'。ts(2769)。useMutation.d.ts(6, 25):最后一个重载声明于此。

错误原因

  1. 泛型参数顺序不匹配:useMutation的泛型定义顺序为useMutation<Data, Error, Variables, Context>,你仅指定了前两个泛型,但第一个泛型BodyInterface与loginUser实际返回的AxiosResponse<any, any>类型不匹配,同时漏传了第三个泛型(即loginUser接收的参数类型),导致TypeScript无法正确推导函数类型,进而误判loginUser为MutationKey类型。
  2. 冗余接口定义:BodyInterface与外部的userInterface结构完全一致,属于重复定义,无存在必要。

修复步骤

  • 修正泛型参数顺序:按照Data, Error, Variables的顺序传入正确类型:
    • Data:对应axios.post返回的AxiosResponse的data字段类型(可根据后端实际返回结构自定义,不确定时可用any或unknown)
    • Error:对应请求失败的错误类型,推荐使用axios提供的AxiosError
    • Variables:对应loginUser接收的参数类型,直接复用外部的userInterface即可
  • 移除冗余接口:删除重复的BodyInterface,统一使用外部定义的类型
  • 明确函数返回类型:给loginUser函数指定返回类型,帮助TypeScript更准确地推导类型

修复后的代码

import { useMutation } from 'react-query';
import axios, { AxiosResponse, AxiosError } from 'axios';

// 统一用户参数类型
interface UserInterface {
  email: string;
  password: string;
}

// 定义登录接口返回的数据类型(根据后端实际返回结构调整)
interface LoginResponseData {
  token: string;
  // 可添加其他返回字段
}

// 明确函数参数与返回类型
const loginUser = (user: UserInterface): Promise<AxiosResponse<LoginResponseData>> => {
  return axios.post('http://127.0.0.0/login', user);
};

export const useLoginApi = () => {
  // 定义错误响应类型(根据后端错误返回结构调整)
  interface ErrorResponse {
    status: string;
    // 可添加其他错误字段
  }

  const {
    mutate: loginUserMutator,
    isError,
    error,
  } = useMutation<AxiosResponse<LoginResponseData>, AxiosError<ErrorResponse>, UserInterface>(loginUser);

  return {
    loginUserMutator,
    isError,
    error,
  };
};

简化写法(可选)

如果不需要精确的类型定义,也可以省略泛型参数,让TypeScript自动推导:

const {
  mutate: loginUserMutator,
  isError,
  error,
} = useMutation(loginUser);

此时TypeScript会自动识别loginUser的参数和返回类型,错误类型默认是unknown,若需要处理错误信息,仍建议显式指定AxiosError类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:31:16