【问题标题】:react-query useMutation onError never firingreact-query useMutation onError 从不触发
【发布时间】:2022-06-22 21:01:04
【问题描述】:

我目前正在我的项目中尝试 react-query。

我在处理我的变异中的错误时遇到了麻烦。

在我的网络选项卡中,我可以确认服务器正在响应代码 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
  },
}

);

【问题讨论】:

  • 您的代码看起来正确,除非您在某处有一些 axios 拦截器,否则这应该可以工作。你能在codesandbox中重现这个吗?
  • 你解决了这个问题吗?我有同样的问题顺便说一句://
  • 支持@TkDodo,这正是原因。我忘了我设置了一个axios拦截器。
  • @mymoto 你得到这个问题了吗?我也面临同样的情况。

标签: javascript reactjs typescript react-query mutation


【解决方案1】:

这可能是因为您以磨损的顺序传递参数。 在文档中它说你应该这样称呼它:

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
  },
}

【讨论】:

    猜你喜欢
    • 2021-11-29
    • 1970-01-01
    • 2022-06-16
    • 2023-04-08
    • 2023-01-24
    • 2021-04-15
    • 2019-07-25
    • 2020-08-14
    • 1970-01-01
    相关资源
    最近更新 更多