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

React Query useMutation+Axios Post返回data为undefined问题求助

问题原因

你的useMutation回调函数没有返回异步请求的Promise,导致React Query无法等待请求完成,自然拿不到返回数据:

  • 你写的是() => {postFunction(rowData)},这个箭头函数里只调用了postFunction,但没有return它的结果。因为postFunction是async函数,调用后会返回Promise,但你没把这个Promise返回给useMutation,所以useMutation会认为异步操作立即完成,直接执行onSuccess,此时Axios的请求还在进行,所以onSuccess里的data是undefined,而且控制台里useMutation的log会比Axios的先打印。

另外注意:你的代码里useMutation用的是postFunction,但Axios请求函数叫editEventLines,如果这两个不是同一个函数,也会导致问题,要确保传入useMutation的是正确的异步请求函数。

修复方案

把回调函数改成返回异步请求函数的调用结果,两种写法都可以:

  1. 去掉花括号,箭头函数自动返回:
const {mutate, isLoading} = useMutation(() => editEventLines(rowData), {
  onSuccess: data => {
    console.log(data)
    alert(data['message'])
  },
  onError: error => {
    alert(error['message'])
  }
})
  1. 显式return:
const {mutate, isLoading} = useMutation(() => {
  return editEventLines(rowData)
}, {
  onSuccess: data => {
    console.log(data)
    alert(data['message'])
  },
  onError: error => {
    alert(error['message'])
  }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:39:23