React Query useMutation钩子TypeScript类型错误:无匹配重载
React Query useMutation 结合 GraphQL 的 TypeScript 类型错误解决
在 TypeScript 项目中使用 react-query 的 useMutation 钩子结合 GraphQL 查询时,遇到了类型不匹配的错误,具体代码和错误信息如下:
示例代码
useMutation( async ( parameter1: string, parameter2: string ) => { const response = await sdk.myMutation({ parameter1: parameter1, parameter2: parameter2, }); return response; }, { onSettled: () => queryClient.invalidateQueries([CACHE_KEY]), } );
类型错误信息
No overload matches this call. Overload 1 of 4, '(mutationFn: MutationFunction<{ __typename: "IdResponse"; id: string; }, string>, options?: Omit<UseMutationOptions<{ __typename: "IdResponse"; id: string; }, unknown, string, unknown>, "mutationFn"> | undefined): UseMutationResult<...>', gave the following error. Argument of type '(parameter1: string, parameter2: string) => Promise<{ __typename: "IdResponse"; id: string; }>' is not assignable to parameter of type 'MutationFunction<{ __typename: "IdResponse"; id: string; }, string>'. Overload 2 of 4, '(mutationKey: MutationKey, options?: Omit<UseMutationOptions<unknown, unknown, void, unknown>, "mutationKey"> | undefined): UseMutationResult<unknown, unknown, void, unknown>', gave the following error. Argument of type '(parameter1: string, parameter2: string) => Promise<{ __typename: "IdResponse"; id: string; }>' is not assignable to parameter of type 'MutationKey'. Overload 3 of 4, '(mutationKey: MutationKey, mutationFn?: MutationFunction<unknown, void> | undefined, options?: Omit<UseMutationOptions<unknown, unknown, void, unknown>, "mutationFn" | "mutationKey"> | undefined): UseMutationResult<...>', gave the following error. Argument of type '(parameter1: string, parameter2: string) => Promise<{ __typename: "IdResponse"; id: string; }>' is not assignable to parameter of type 'MutationKey'.
问题原因
react-query 的 MutationFunction 类型仅允许接收单个参数,当前代码给 mutationFn 传入了两个独立参数,不符合类型定义要求,导致 TypeScript 抛出类型不匹配错误。
解决方法
将多个参数合并为一个对象,作为 mutationFn 的唯一参数即可解决问题:
修改后的代码
// 可选:定义参数类型,让类型约束更明确 interface MutationParams { parameter1: string; parameter2: string; } useMutation( async ({ parameter1, parameter2 }: MutationParams) => { const response = await sdk.myMutation({ parameter1, parameter2, }); return response; }, { onSettled: () => queryClient.invalidateQueries([CACHE_KEY]), } );
调用 mutation 时的写法
后续调用该 mutation 时,需要传入包含对应字段的对象:
// 假设 mutation 实例为 mutate mutate({ parameter1: "value1", parameter2: "value2" });
这样既满足了 TypeScript 的类型约束,又能正常执行 GraphQL 突变操作。
内容的提问来源于stack exchange,提问作者James Brunskill
相关产品推荐
相关产品推荐

