使用TanStack React Query的useMutation遇类型不匹配错误求助
TanStack React Query useMutation 类型不匹配问题解决
问题场景
使用TanStack React Query的useMutation钩子向数据库添加部门时,出现类型不匹配错误。
相关代码
addDepartment函数
import { useQuery, useMutation } from '@tanstack/react-query'; async function addDepartment(deptData: deptFormSchemaType): Promise<any> { const response = await fetch('/api/department', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(deptData), }); if (!response.ok) { throw new Error('Failed to add department'); } return response.json(); }
useMutation 钩子使用
const {mutate} = useMutation(addDepartment, { onSuccess: () => {toast.success('Department added successfully'); form.reset(); updateSelectedEmployees(); setIsLoading(false);}, onError: () => {toast.error('Error adding department');} })
错误信息
在useMutation(addDepartment处出现类型错误:
Type '(deptData: { name: string; description: string; dept_head: string; max_teams: number; members?: string[] | undefined; }) => Promise<any>' has no properties in common with type 'UseMutationOptions<unknown, Error, void, unknown>'.ts(2559) (local function) addDepartment(deptData: deptFormSchemaType): Promise<any>
解决方案
1. 适配TanStack Query v4+ API写法
TanStack React Query v4及以上版本调整了useMutation的API结构,不再支持useMutation(mutationFn, options)的参数分离写法,需要将所有配置(包括mutationFn)放入同一个配置对象中:
const { mutate } = useMutation({ mutationFn: addDepartment, onSuccess: () => { toast.success('Department added successfully'); form.reset(); updateSelectedEmployees(); setIsLoading(false); }, onError: () => { toast.error('Error adding department'); } });
2. 显式指定泛型(可选,增强类型安全)
如果需要更严格的类型校验,可以为useMutation指定泛型参数,分别对应返回数据类型、错误类型、入参类型:
// 先定义接口匹配后端返回的部门数据结构 type DepartmentResponse = { id: string; name: string; description: string; // 其他字段根据实际返回补充 }; const { mutate } = useMutation<DepartmentResponse, Error, deptFormSchemaType>({ mutationFn: addDepartment, onSuccess: (data) => { // 此时data会有完整的类型提示 toast.success('Department added successfully'); form.reset(); updateSelectedEmployees(); setIsLoading(false); }, onError: (error) => { // error为Error类型,可直接使用error.message等属性 toast.error(`Error adding department: ${error.message}`); } });
错误原因
这个类型错误是因为你使用了TanStack Query v4+版本,但沿用了v3版本的useMutation调用方式。v4将useMutation的参数统一为单一配置对象,旧的参数分离写法不符合新的类型定义,因此触发TypeScript报错。
内容的提问来源于stack exchange,提问作者Noor Fatima
相关产品推荐
相关产品推荐

