useMutation() status is stuck in 'pending' when call from useEffect() #9068
Send to my agentDescribe the bug#
I'm calling mutate() in the useEffect() of a component.
Basically I want to invoke something when opening a modal - so I cannot react on the button click, if the mutation should be in the modal itself.
The loading works, onSuccess() & onSettled() are called. But mutation.status & mutation.data are not updated.
I'm a little bit puzzled, because it seems to work, when just using the onSuccess. But any real logic which involves the status (and all derived isXyz-props) does not work anymore.
Your minimal, reproducible example#
https://stackblitz.com/edit/vitejs-vite-arwygstx?file=src%2FApp.tsx
Steps to reproduce#
- Click on "Open Auto"
- The "Modal" opens
- After the promise resolves, the data from the callback is changed, the status not.
Expected behavior#
The behavior should be consistent. Either the callbacks & status works. Or both don't work. The first option is preferred ;)
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
Current Chrome on Ubuntu Linux
Tanstack Query adapter#
react-query
TanStack Query version#
v5.74.4
TypeScript version#
No response
Additional context#
No response
wait I think I know why this happens. We use
useStateto initialize ourobserver, and this also gets initialized twice instrictMode. So when you only executemutateon the “first observer”, it’s no longer tracked because the observer is destroyedmy PR doesn’t fix it, I guess it’s because the
useSyncExternalStoresubscription also gets re-done by react.Best I can offer right now is to a) not do the ref workaround as it’s more harm than good or b) call
useMutationState, as this should work as expected.Generally, I’d think mutations shouldn’t be dependent on rendering. They update something on the server and an effect is often the wrong abstraction.
useEffectEventmight help, it only runs once.In your simplified example, the solution is obviously to run the mutation when the button is clicked, but I understand that real examples are likely more complicated.
TkDodo closed this
TkDodo added labelswontfix
TkDodo added labelshas workaround
Thanks for looking into it & giving your explanation.
Sign in to join this conversation.
This is happening because you’re using the ref-workaround to stop the mutation from firing a second time in strict mode.
useMutationkeeps track of the latest mutation invocation, and this somehow gets out-of-sync.There’s no issue in production, or outside of StrictMode, or if you remove the workaround (you’ll see the mutation fire twice, and status tracks correctly)
The callbacks “work” because they are cache level callbacks that will always fire, even if the mutation unmounts. There are callbacks for
onMutatethat behave the same way as the status (they won’t fire).