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

TypeScript报错:类型'{ onSuccess: () => void; }'无'mutateAsync'属性

问题:添加onSuccess回调后出现TypeScript错误 Property 'mutateAsync' does not exist...

原本正常运行的两个mutation,添加onSuccess回调并调用invalidateQueries后,出现如下TypeScript错误:

Property 'mutateAsync' does not exist on type '{ onSuccess: () => void; }

相关hooks代码

export const useAddUserContact = () => {

    const queryClient = useQueryClient();

    return useMutation(
        (user: any) => axios.post("http://localhost:4000/userContacts", user)
            .then(response => response.data)
    ),
    {
        onSuccess: () => {
            queryClient.invalidateQueries([userContacts.fetchUserContacts])
        }
    }
};

export const useDeleteUserContact = () => {

    const queryClient = useQueryClient();

    return useMutation(
        (userId: string) => axios.delete(`http://localhost:4000/userContacts/${userId}`)
            .then(response => response.data)
    ),
    {
        onSuccess: () => {
            queryClient.invalidateQueries([userContacts.fetchUserContacts])
        }
    }
};

hooks使用代码

const {
    mutateAsync: addUserContactMutation
} = useAddUserContact();

const addContactOnClickHandler = (contact: User) => {
    addUserContactMutation(contact);
};

解决方案

问题根源是return语句的语法错误:你把useMutation的调用和配置对象用逗号分隔,导致实际返回的是逗号表达式的结果(仅返回后面的{ onSuccess: ... }对象),而非useMutation提供的包含mutateAsync的完整mutation实例。

useMutation的正确用法是将配置对象作为第二个参数传入,而非单独放在return语句里。修正后的代码如下:

export const useAddUserContact = () => {
    const queryClient = useQueryClient();

    return useMutation(
        // 第一个参数:mutation执行函数
        (user: any) => axios.post("http://localhost:4000/userContacts", user)
            .then(response => response.data),
        // 第二个参数:配置对象(包含onSuccess等回调)
        {
            onSuccess: () => {
                queryClient.invalidateQueries([userContacts.fetchUserContacts])
            }
        }
    );
};

export const useDeleteUserContact = () => {
    const queryClient = useQueryClient();

    return useMutation(
        (userId: string) => axios.delete(`http://localhost:4000/userContacts/${userId}`)
            .then(response => response.data),
        {
            onSuccess: () => {
                queryClient.invalidateQueries([userContacts.fetchUserContacts])
            }
        }
    );
};

修正后,useMutation会正确返回包含mutateAsync的mutation对象,TypeScript的错误即可解决。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:41:58