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
相关产品推荐
相关产品推荐

