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 1 commit 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 1 commit 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.

Closes #8060

Summary by CodeRabbit

  • Bug Fixes
    • Improved query fetching when an in-progress request is invalidated and refetched.
    • Imperative fetches now resolve with the latest successful result instead of incorrectly failing due to a silent cancellation.
    • Preserved cancellation behavior when a query is explicitly destroyed.

…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

📝 Walkthrough

Walkthrough

Query now follows superseding fetch promises after silent cancellation. A regression test verifies that an imperative fetchQuery resolves successfully 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

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main query-core behavior change and matches the implemented fix.
Description check ✅ Passed The description explains the problem, fix, and test coverage, though it omits the template's checklist and release-impact sections.
Linked Issues check ✅ Passed The code and test changes address #8060 by making superseded imperative fetches resolve with the latest result instead of a silent CancelledError.
Out of Scope Changes check ✅ Passed The changes stay focused on the reported fetch cancellation bug and its regression test, with no unrelated additions.
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

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

1 participant