Skip to content

fix(router-core): guard against evicted matches during in-flight preloads#7762

Open
thribhuvan003 wants to merge 2 commits into
TanStack:mainfrom
thribhuvan003:fix/preload-evicted-match-guards
Open

fix(router-core): guard against evicted matches during in-flight preloads#7762
thribhuvan003 wants to merge 2 commits into
TanStack:mainfrom
thribhuvan003:fix/preload-evicted-match-guards

Conversation

@thribhuvan003

@thribhuvan003 thribhuvan003 commented Jul 8, 2026

Copy link
Copy Markdown

when a preload's cached match gets evicted while its async work is still in flight (cache cleared, gc'd, or the user actually navigates mid-preload), the load pipeline re-looks the match up after each await with a non-null assertion, so the next ._nonReactive read throws TypeError: Cannot read properties of undefined (reading '_nonReactive') as an unhandled rejection.

this guards those re-lookups the same way executeHead and runLoader's catch already do. the post-load cleanup falls back to the matched object instead of bailing — _nonReactive keeps its identity across store updates, so resolving the promises on it means a second load awaiting the first one's loaderPromise still settles instead of hanging forever (that hang is real: the second regression test times out without the fix).

added two deterministic tests (evict mid-loader, and a second preload joining the in-flight load). both fail without the fix, and router-core (1186) + react-router (912) suites pass with it.

fixes #7759

Summary by CodeRabbit

  • Bug Fixes

    • Hardened route preloading and loader flow to safely handle cached match eviction during in-flight operations.
    • Prevented crashes and ensured preload/loader promises settle cleanly even when the underlying match disappears mid-load.
  • Tests

    • Added coverage for cache eviction during active preloads, including repeated preload calls, verifying both promises settle without error logging.

@coderabbitai

coderabbitai Bot commented Jul 8, 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

Run ID: eb8bf935-7dca-434a-a8d1-3a9742bca84c

📥 Commits

Reviewing files that changed from the base of the PR and between 51fe6a1 and bb4816f.

📒 Files selected for processing (1)
  • packages/router-core/src/load-matches.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/router-core/src/load-matches.ts

📝 Walkthrough

Walkthrough

This PR guards several getMatch(matchId) lookups in load-matches.ts that previously used non-null assertions, replacing them with nullable checks and fallbacks to the in-scope match object so in-flight preload promises settle safely after a cached match is evicted. Adds regression tests and a changeset.

Changes

Preload eviction guard fix

Layer / File(s) Summary
Guard beforeLoad continuation
packages/router-core/src/load-matches.ts
preBeforeLoadSetup and executeBeforeLoad replace non-null getMatch(...)! with nullable lookups and early returns when a match is evicted mid-await.
Guard background reload and in-flight loader await
packages/router-core/src/load-matches.ts
Background stale-while-revalidate path falls back to inner.matches[index]!, and in-flight loader await only processes redirect/notFound/pending handling if the match still exists.
Guard loadRouteMatch finalization and return
packages/router-core/src/load-matches.ts
loadRouteMatch finalization and its returned match fall back to the local match object instead of assuming getMatch(...) always returns a value.
Eviction regression tests and changeset
packages/router-core/tests/load.test.ts, .changeset/fix-preload-evicted-match-guards.md
New test suite verifies preloadRoute settles without console errors when cache is cleared mid-load; changeset documents the patch and references issue #7759.

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

Sequence Diagram(s)

sequenceDiagram
  participant preloadRoute
  participant loadMatches
  participant routerStore

  preloadRoute->>loadMatches: start in-flight preload
  loadMatches->>routerStore: getMatch(matchId)
  routerStore-->>loadMatches: undefined after eviction
  loadMatches->>loadMatches: fall back to inner.matches[index] or return early
  loadMatches-->>preloadRoute: settle promise without _nonReactive crash
Loading

Possibly related issues

Suggested labels: package: router-core

Suggested reviewers: nlynzaad, Sheraff

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is specific, concise, and accurately summarizes the main router-core preload eviction fix.
Linked Issues check ✅ Passed The code and tests address #7759 by guarding post-await match lookups and covering eviction during in-flight preloads.
Out of Scope Changes check ✅ Passed The changes stay focused on the preload-eviction fix, with only the needed code, tests, and changeset entry.
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/router-core/src/load-matches.ts (1)

373-375: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use curly braces for one-line if bodies.

Lines 375 and 399 use if (!match) return without braces. The project's coding guidelines require curly braces for all control statements.

As per coding guidelines: "Always use curly braces for if, else, loops, and similar control statements. Never write one-line bodies like if (foo) x = 1."

♻️ Proposed fix
   const then = () => {
     const match = inner.router.getMatch(matchId)
     // in case the match was evicted while awaiting the previous beforeLoad
-    if (!match) return
+    if (!match) {
+      return
+    }
 const executeBeforeLoad = (
   inner: InnerLoadContext,
   matchId: string,
   index: number,
   route: AnyRoute,
 ): void | Promise<void> => {
   const match = inner.router.getMatch(matchId)
   // in case the match was evicted while `preBeforeLoadSetup` was awaiting the
   // previous beforeLoad
-  if (!match) return
+  if (!match) {
+    return
+  }

Also applies to: 396-399

🤖 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/router-core/src/load-matches.ts` around lines 373 - 375, The
control-flow guards in load-matches.ts use one-line if bodies without braces,
which violates the project style guide. Update the match eviction checks around
the getMatch lookup in the load-matches flow to use curly braces for the if
statements, including the related guard near the later match handling path
referenced by the same logic. Keep the behavior unchanged while rewriting those
conditional early returns in the functions that handle match loading.

Source: Coding guidelines

🤖 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/router-core/src/load-matches.ts`:
- Around line 373-375: The control-flow guards in load-matches.ts use one-line
if bodies without braces, which violates the project style guide. Update the
match eviction checks around the getMatch lookup in the load-matches flow to use
curly braces for the if statements, including the related guard near the later
match handling path referenced by the same logic. Keep the behavior unchanged
while rewriting those conditional early returns in the functions that handle
match loading.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3ae4f2a0-ca21-44e2-8e6f-edbddf77bfa1

📥 Commits

Reviewing files that changed from the base of the PR and between a3e24c3 and 51fe6a1.

📒 Files selected for processing (3)
  • .changeset/fix-preload-evicted-match-guards.md
  • packages/router-core/src/load-matches.ts
  • packages/router-core/tests/load.test.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.

TypeError: Cannot read properties of undefined (reading '_nonReactive') from preloadRoute when an in-flight preload's match is evicted

1 participant