Describe the bug#
Consuming an AbortSignal does enable automatic query cancellation if suspense mode is used. When the component unmounts while the query function is not resolved the query is visible in the dev tools without any observers.
Your minimal, reproducible example#
https://codesandbox.io/s/magical-shape-hbf7l4
Steps to reproduce#
- load the sandbox
- wait for the timeout / until the page shows “done“
- the console is still empty because there was no abort event on the signal
Expected behavior#
I expected that the automatic cancellation works both for suspense: false and suspense: true. That includes the unobserved query being garbage collected.
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
- OS: Linux
- Browser: Firefox
TanStack Query version#
4.26.1
TypeScript version#
4.1.3
Additional context#
From what I can tell be glancing at the problem this has to do with useSyncExternalStore which is used by useQuery. When the component suspends React never subscribes and consequently never unsubscribes which would trigger removing the observer and in turn abort being called.
Yeah I don't think this can work. Query cancellation works on observer level. If the last observer unsubscribes while the query is in-flight, the query will be cancelled.
With suspense, we never get to the point where the observer even subscribes, because suspending happens up-front.
I don't think there is a way how we can distinguish between "the component unmounts because of suspense" vs. "the component unmounts because I'm not rendering it". If you have a component that unmounts the suspense boundary, I would setup a
useEffectthere that callsqueryClient.cancelQueries({ queryKey })manually.