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

React+TypeScript+ReactQuery中Mutation函数Props类型定义报错求助

报错原因分析
  1. mutate参数结构不匹配:React Query的useMutation返回的mutate函数仅接受单个参数,但你在IPropertyAPI里定义的mutate是多个零散参数,TypeScript检测到类型不兼容。
  2. 参数顺序混乱:你定义的mutate第一个参数是id,但实际useMutation里的请求函数第一个参数是ordering,顺序完全颠倒,加剧了类型不匹配。
  3. 错误传递onSuccess:onSuccess是useMutation的配置项参数,不是mutate的调用参数,你把它放到mutate参数里是错误的。
  4. 类型宽泛无意义:大量使用any导致TypeScript无法发挥类型检查作用,也会引发类型推导错误。
解决方案

1. 定义请求参数和响应数据的类型

先把零散的请求参数整合成一个对象类型,同时定义API返回数据的类型:

// 定义请求参数类型
interface GetPropertiesParams {
  id?: string;
  statusId?: string;
  typeId?: string;
  rooms?: string;
  neighborhood?: string;
  district?: string;
  priceMin?: string;
  priceMax?: string;
  createdAtAfter?: string;
  createdAtBefore?: string;
  ordering?: string;
}

// 定义API返回数据的类型(根据实际接口返回结构调整)
interface Property {
  id: string;
  name: string;
  // 补充其他属性...
}

interface GetPropertiesResponse {
  data: Property[];
  // 补充其他响应字段...
}

2. 修正IPropertyAPI接口定义

直接复用React Query的UseMutationResult类型,避免自己定义不一致的结构:

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

export interface IPropertyAPI {
  useGetProperties: () => UseMutationResult<GetPropertiesResponse, unknown, GetPropertiesParams>;
  useGetDetails: () => UseMutationResult</* 填入详情接口的响应类型 */, unknown, string>;
}

3. 修正useMutation的实现

  • 让请求函数接收单个参数对象,和定义的GetPropertiesParams匹配
  • 用URLSearchParams安全拼接URL,自动过滤undefined参数:
import axios from 'axios';
import { useMutation } from '@tanstack/react-query';

export const propertyAPI: IPropertyAPI = {
  useGetProperties: () => useMutation({
    mutationKey: ['getProperties'],
    mutationFn: (params: GetPropertiesParams) => {
      const searchParams = new URLSearchParams({ offset: '20' });
      Object.entries(params).forEach(([key, value]) => {
        if (value) {
          // 注意:这里根据后端接口调整参数名,比如原代码中id对应propertyId
          searchParams.append(key === 'id' ? 'propertyId' : key, value);
        }
      });
      return axios.get<GetPropertiesResponse>(`/estates/?${searchParams.toString()}`);
    },
    onSuccess: (data) => {
      // 全局成功回调(可选)
    }
  }),
  // 补充useGetDetails的实现示例
  useGetDetails: () => useMutation({
    mutationKey: ['getPropertyDetails'],
    mutationFn: (id: string) => axios.get(`/estates/${id}`)
  })
};

4. 组件中调用的方式

现在调用mutate时只需传入参数对象即可:

const { mutate, isLoading, data } = propertyAPI.useGetProperties();

// 调用示例
mutate({
  id: '123',
  ordering: '-createdAt',
  priceMin: '1000'
});

// 如需组件内自定义成功回调,可在调用时传入
mutate(
  { id: '123' },
  {
    onSuccess: (data) => {
      // 组件内的成功逻辑
    }
  }
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 01:20:36