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

如何在表单提交时向React Query的useMutation钩子传递输入参数?

解决useMutation调用登录函数的类型错误问题

我在表单提交时尝试调用登录用的mutation,登录函数代码如下:

export const login = async (email : string , password : string) => {
  
  const response = await  axios.post(`${BASE_URL}/users/login` , {"user":{email:email, password:password}});

  return response.data;

}

我原本的调用代码:

const { mutate, isLoading , error} = useMutation(variables => login(variables.email , variables.password))

表单提交事件处理代码:

onSubmit={(values) => {
    console.log(values);
    mutate({email : values.email , password:values.password});
  }} 

运行后出现以下错误:

Property 'email' does not exist on type 'void'.
Property 'password' does not exist on type 'void'.
Argument of type '{ email: string; password: string; }' is not assignable to parameter of type 'void'.


错误原因

TypeScript无法自动推导useMutation接收的变量类型,默认将变量类型判定为void,导致传入对象参数时类型不匹配。

正确实现方式

方式一:显式定义变量与返回值类型

给useMutation指定泛型参数,明确变量结构和接口返回值类型:

// 定义登录参数类型
type LoginParams = {
  email: string;
  password: string;
};

// 定义登录接口返回数据类型(根据实际接口返回调整)
type LoginResponse = {
  user: {
    token: string;
    // 其他返回字段...
  };
};

// 带类型的useMutation调用
const { mutate, isLoading, error } = useMutation<LoginResponse, Error, LoginParams>(
  (params) => login(params.email, params.password)
);

方式二:修改登录函数接收对象参数

调整login函数的参数形式,直接接收包含邮箱和密码的对象,让TypeScript自动推导类型:

// 修改后的login函数
export const login = async ({ email, password }: { email: string; password: string }) => {
  const response = await axios.post(`${BASE_URL}/users/login`, { user: { email, password } });
  return response.data;
};

// 直接传入login函数给useMutation
const { mutate, isLoading, error } = useMutation(login);

两种方式下,表单提交的代码都可以保持原样不变:

onSubmit={(values) => {
  console.log(values);
  mutate({ email: values.email, password: values.password });
}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:15:47