Skip to content

fix(query-core): don't reject imperative fetch with CancelledError when a superseding fetch is started - #11061

Open
xianjianlf2 wants to merge 4 commits into
TanStack:mainfrom
xianjianlf2:fix/fetchquery-cancelled-on-invalidate-8060
Open

fix(query-core): don't reject imperative fetch with CancelledError when a superseding fetch is started#11061
xianjianlf2 wants to merge 4 commits into
TanStack:mainfrom
xianjianlf2:fix/fetchquery-cancelled-on-invalidate-8060

Conversation

@xianjianlf2

@xianjianlf2 xianjianlf2 commented Jul 13, 2026

Copy link
Copy Markdown

Problem

When a fetch is silently cancelled because a new fetch supersedes it (e.g.
invalidateQueries refetching an active observer with cancelRefetch: true),
callers that joined the in-flight fetch via the early-return in Query.fetch
received the raw retryer promise, which rejects with a silent CancelledError.

The async fetch body already piggybacks onto the superseding fetch on silent
cancellation, but the early-return path bypassed it, so an imperative
fetchQuery could reject with a CancelledError even though the query
continued fetching.

Fix

Route both the early-return and the catch-block piggyback through a shared
helper that follows the chain of superseding fetches until one settles, while
still rethrowing when the silent cancellation isn't from a superseding fetch
(e.g. query destroyed).

Testing

Added a regression test in packages/query-core/src/__tests__/queryClient.test.tsx
covering the scenario where an imperative fetch is superseded by an
invalidateQueries-triggered refetch, asserting the imperative call resolves
with the fresh data instead of rejecting with a CancelledError.

Checklist

  • Added regression coverage for the superseding-fetch path
  • Preserved the existing silent-cancellation behavior for destroyed queries
  • Kept the change scoped to query-core

Release Impact

Low risk bug fix in query-core. The change only corrects how imperative fetches
follow a superseding refetch; it should not affect callers outside the failed
CancelledError path.

Closes #8060

Summary by CodeRabbit

  • Bug Fixes

    • Fixed query fetching when an in-progress request is invalidated and refetched, ensuring the latest result is used.
    • Prevented silently cancelled fetches from failing incorrectly when a newer request supersedes them.
    • Preserved existing cancellation behavior when a query is explicitly destroyed.
  • Tests

    • Added regression coverage for fetch resolution during invalidation while an active query is refetching.

…en a superseding fetch is started

When a fetch is silently cancelled because a new fetch supersedes it (e.g.
`invalidateQueries` refetching an active observer with `cancelRefetch: true`),
callers that joined the in-flight fetch via the early-return in `Query.fetch`
received the raw retryer promise, which rejects with a silent `CancelledError`.
The async `fetch` body already piggybacks onto the superseding fetch on silent
cancellation, but the early-return path bypassed it.

Route both the early-return and the catch-block piggyback through a shared
helper that follows the chain of superseding fetches until one settles, while
still rethrowing when the silent cancellation isn't from a superseding fetch
(e.g. query destroyed).

Closes TanStack#8060
@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 76abfcd3-bbf8-4078-a415-01a42dc64d96

📥 Commits

Reviewing files that changed from the base of the PR and between b8e3559 and 20eacbc.

📒 Files selected for processing (2)
  • packages/query-core/src/__tests__/queryClient.test.tsx
  • packages/query-core/src/query.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/query-core/src/tests/queryClient.test.tsx
  • packages/query-core/src/query.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

Query now follows superseding fetch promises after silent cancellation. A regression test verifies that fetchQuery resolves with the superseding result when invalidation triggers an active observer refetch.

Changes

Silent cancellation continuation

Layer / File(s) Summary
Superseding fetch promise handling
packages/query-core/src/query.ts, packages/query-core/src/__tests__/queryClient.test.tsx
Query follows replacement retryer promises for silent cancellations and in-flight fetch callers. A test covers invalidation during an imperative fetch with an active observer refetch.

Estimated code review effort: 3 (Moderate) | ~15 minutes

Merge Risk: ⚪ Minimal · up to 20eac

The change makes imperative fetches follow superseding refetches instead of surfacing a cancellation error; no actionable merge-blocking risk remains beyond normal checks and review.

Sequence Diagram(s)

sequenceDiagram
  participant QueryClient
  participant Query
  participant QueryObserver
  QueryClient->>Query: start imperative fetch
  QueryObserver->>Query: refetch after invalidation
  Query-->>Query: silently cancel superseded retryer
  Query-->>QueryClient: follow latest retryer promise
  Query-->>QueryClient: resolve with superseding result
Loading

Possibly related PRs

Suggested labels: package: query-core

Suggested reviewers: sukvvon

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main fix for superseded imperative fetches.
Description check ✅ Passed The description explains the problem, fix, testing, checklist, and release impact, with sufficient detail for review.
Linked Issues check ✅ Passed The implementation and regression test address issue #8060 by resolving fetchQuery with the superseding fetch result.
Out of Scope Changes check ✅ Passed The changes are limited to the query-core implementation and its regression test, which match the linked issue scope.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/query-core/src/__tests__/queryClient.test.tsx (1)

1060-1094: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Strengthen the assertion to verify fresh data from the superseding fetch.

expect.any(Number) would pass even if fetchPromise resolved with stale data from the priming fetch (count = 1) instead of fresh data from the superseding fetch (count = 2). Asserting the specific value verifies the correct fetch result is propagated.

♻️ Proposed fix
-    await expect(fetchPromise).resolves.toEqual(expect.any(Number))
+    await expect(fetchPromise).resolves.toBe(2)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/query-core/src/__tests__/queryClient.test.tsx` around lines 1060 -
1094, Strengthen the final assertion in the invalidation/refetch test so
fetchPromise resolves specifically to 2, confirming it receives the superseding
fetch’s fresh result rather than the priming result of 1. Keep the existing test
flow and cleanup unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/query-core/src/__tests__/queryClient.test.tsx`:
- Around line 1060-1094: Strengthen the final assertion in the
invalidation/refetch test so fetchPromise resolves specifically to 2, confirming
it receives the superseding fetch’s fresh result rather than the priming result
of 1. Keep the existing test flow and cleanup unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 58990ea9-f848-48e9-8acb-57928aedf22e

📥 Commits

Reviewing files that changed from the base of the PR and between 79d2384 and b51699f.

📒 Files selected for processing (2)
  • packages/query-core/src/__tests__/queryClient.test.tsx
  • packages/query-core/src/query.ts

@xianjianlf2

Copy link
Copy Markdown
Author

Addressed the assertion-strengthening review in 2c8a3ec. I used toBe(3) rather than toBe(2) after verifying the sequence locally: 1 is the priming fetch, 2 is the observer's background refetch, and the invalidate-triggered superseding fetch resolves to 3.\n\nLocal check:\n- PATH=/Users/even/.nvm/versions/node/v24.18.0/bin:/Users/even/.nvm/versions/node/v20.20.2/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin:/opt/pmk/env/global/bin:/Library/Apple/usr/bin:/Users/even/.codex/tmp/arg0/codex-arg0VOKUrl:/Users/even/.cache/codex-runtimes/codex-primary-runtime/dependencies/bin/override:/Users/even/.bun/bin:/Users/even/.local/bin:/Users/even/.nvm/versions/node/v20.20.2/bin:/Users/even/.cargo/bin:/Users/even/.cache/codex-runtimes/codex-primary-runtime/dependencies/bin/fallback:/Applications/ChatGPT.app/Contents/Resources pnpm --dir packages/query-core test:lib src/__tests__/queryClient.test.tsx

Comment thread packages/query-core/src/query.ts Outdated
@nx-cloud

nx-cloud Bot commented Aug 18, 2026

Copy link
Copy Markdown

View your CI Pipeline Execution ↗ for commit 20eacbc

Command Status Duration Result
nx affected --targets=test:sherif,test:knip,tes... ✅ Succeeded 5m 59s View ↗
nx run-many --target=build --exclude=examples/*... ✅ Succeeded 46s View ↗

☁️ Nx Cloud last updated this comment at 2026-08-18 19:33:57 UTC

@coderabbitai

coderabbitai Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@pkg-pr-new

pkg-pr-new Bot commented Aug 18, 2026

Copy link
Copy Markdown
More templates

@tanstack/angular-query-experimental

npm i https://pkg.pr.new/@tanstack/angular-query-experimental@11061

@tanstack/eslint-plugin-query

npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@11061

@tanstack/lit-query

npm i https://pkg.pr.new/@tanstack/lit-query@11061

@tanstack/preact-query

npm i https://pkg.pr.new/@tanstack/preact-query@11061

@tanstack/preact-query-devtools

npm i https://pkg.pr.new/@tanstack/preact-query-devtools@11061

@tanstack/preact-query-persist-client

npm i https://pkg.pr.new/@tanstack/preact-query-persist-client@11061

@tanstack/query-async-storage-persister

npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@11061

@tanstack/query-broadcast-client-experimental

npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@11061

@tanstack/query-core

npm i https://pkg.pr.new/@tanstack/query-core@11061

@tanstack/query-devtools

npm i https://pkg.pr.new/@tanstack/query-devtools@11061

@tanstack/query-persist-client-core

npm i https://pkg.pr.new/@tanstack/query-persist-client-core@11061

@tanstack/query-sync-storage-persister

npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@11061

@tanstack/react-query

npm i https://pkg.pr.new/@tanstack/react-query@11061

@tanstack/react-query-devtools

npm i https://pkg.pr.new/@tanstack/react-query-devtools@11061

@tanstack/react-query-next-experimental

npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@11061

@tanstack/react-query-persist-client

npm i https://pkg.pr.new/@tanstack/react-query-persist-client@11061

@tanstack/solid-query

npm i https://pkg.pr.new/@tanstack/solid-query@11061

@tanstack/solid-query-devtools

npm i https://pkg.pr.new/@tanstack/solid-query-devtools@11061

@tanstack/solid-query-persist-client

npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@11061

@tanstack/svelte-query

npm i https://pkg.pr.new/@tanstack/svelte-query@11061

@tanstack/svelte-query-devtools

npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@11061

@tanstack/svelte-query-persist-client

npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@11061

@tanstack/vue-query

npm i https://pkg.pr.new/@tanstack/vue-query@11061

@tanstack/vue-query-devtools

npm i https://pkg.pr.new/@tanstack/vue-query-devtools@11061

commit: 20eacbc

@TkDodo TkDodo left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I forked the initial reproduction from the issue and used the preview build to check it, but it seems to still throw the same unexpected CancelledError:

https://codesandbox.io/p/devbox/react-query-cancellederror-on-invalidation-forked-ymg4jw?workspaceId=ws_XiBCv7MgHSszKyXHXG5ray

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

invalidateQueries inconsistently cancels fetchQuery

2 participants