typescript react-query useMutation onError从不触发

lxkprmvk  于 2022-11-18  发布在  TypeScript
关注(0)|答案(2)|浏览(226)

我目前正在我的项目中试用react-query。
我在处理我的变异中的错误时遇到了麻烦。
在我的networks选项卡中,我可以确认服务器正在响应代码400或500,我假设这会使axios抛出一个错误,从而触发定义的onError函数。
但是,无论API调用如何进行,始终会调用onSuccess函数。
我错过了什么?提前谢谢你。

const { mutate } = useMutation(
['mutation'],
() => axios.patch(API_URL, params),
{
  onSuccess: () => {
    //this is always fired, even when response code is 400, 500, etc.
    void queryClient.invalidateQueries('query');
  },
  onError: () => {
    //should do something but never fired
  },
}

);

oalqel3c

oalqel3c1#

确保返回变异函数的结果。

const { mutate } = useMutation(['mutation'], () => return axios.patch(API_URL, params),
{
  onSuccess: () => {
    //this is always fired, even when response code is 400, 500, etc.
    void queryClient.invalidateQueries('query');
  },
  onError: () => {
    //should do something but never fired
  },
})
eit6fx6z

eit6fx6z2#

这可能是因为你传递参数的顺序不对。在文档中,它说你应该如下调用它:

useMutation(mutationFn, {
   mutationKey,
   onError,
   onMutate,
   onSettled,
   onSuccess,
   retry,
   retryDelay,
   useErrorBoundary,
   meta,
 });

这使得您的代码如下所示:

useMutation(
() => axios.patch(API_URL, params),
{
  mutationKey: 'mutation',
  onSuccess: () => {
    //this is always fired, even when response code is 400, 500, etc.
    void queryClient.invalidateQueries('query');
  },
  onError: () => {
    //should do something but never fired
  },
}

相关问题