react-router: hydrating an SSR-errored match throws (React error #520); `MatchInner` renders the error component on the server but `throw`s on the client
Maintainer thường phản hồi trong vòng 1 ngày
Đánh giá
- Độ khó
- 3/5
- Thời gian dự kiến
- Nửa ngày
- Mức phù hợp với người mới
- 58/100
- Loại issue
- Lỗi
- Độ rõ ràng
- Đặc tả rõ ràng
- Mức độ hoạt động
- Sôi nổi
- Công nghệ
- react, typescript
- Lĩnh vực
- frontend
Hướng nghiên cứu
The bug is in the status === 'error' branch of MatchInner in packages/react-router/src/Match.tsx, where the server renders the error component but the client throws match.error. Reproduce with the SSR-then-hydrate script in the issue, using jsdom, and watch for the recoverable error and console error. Done when hydrating the server HTML reports no recoverable error, the error component stays rendered, and router.invalidate() still re-runs the loader. Confirm the reset behaviour with a maintainer before opening a pull request.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Mô tả
Versions
@tanstack/react-router1.170.41 and 1.170.46 (identical code inMatch.js/Match.cjs)@tanstack/router-core1.171.34react/react-dom19.3.0
Summary
When a route loader throws during SSR and the route has an errorComponent (or the router has a defaultErrorComponent), the server renders the error component directly. On the client, MatchInner does throw match.error for the same errored match instead of rendering the error component, so hydration of the server-rendered error UI throws. React recovers by client-rendering the whole root and reports the failure through onRecoverableError as minified error #520 ("There was an error during concurrent rendering but React was able to recover by instead synchronously rendering the entire root."), with the route error as its cause. The throw also reaches the route's CatchBoundary, so React's default onCaughtError logs the route error to the console.
The server branch and the client branch of the same if (match.status === "error") block disagree about what an errored match renders. Server-rendered HTML for an errored match is therefore never hydratable without a recoverable error.
Minimal repro
import { createRootRoute, createRoute, createRouter, Outlet } from "@tanstack/react-router";
import { RouterServer, renderRouterToString } from "@tanstack/react-router/ssr/server";
import { RouterClient } from "@tanstack/react-router/ssr/client";
import { createRequestHandler } from "@tanstack/router-core/ssr/server";
import { hydrateRoot } from "react-dom/client";
const rootRoute = createRootRoute({ component: Outlet });
const indexRoute = createRoute({
getParentRoute: () => rootRoute,
path: "/",
loader: () => {
throw new Error("loader failed");
},
errorComponent: ({ error }) => <p role="alert">Failed: {error.message}</p>,
component: () => <p>ok</p>,
});
const routeTree = rootRoute.addChildren([indexRoute]);
const makeRouter = () => createRouter({ routeTree });
// 1. Server: the loader throws, the errorComponent is rendered into the HTML.
const response = await createRequestHandler({
request: new Request("http://localhost/"),
createRouter: makeRouter,
})(({ request, router, responseHeaders }) =>
renderRouterToString({
request,
router,
responseHeaders,
children: <RouterServer router={router} />,
}),
);
const html = await response.text();
// 2. Client (jsdom or a browser): load `html` as the document, then hydrate.
const recoverable: unknown[] = [];
hydrateRoot(document, <RouterClient router={makeRouter()} />, {
onRecoverableError: (error) => recoverable.push(error),
});
Observed
recoverableis[Error("There was an error during concurrent rendering but React was able to recover by instead synchronously rendering the entire root.")]withcauseset to the dehydrated route error.- The error is thrown from
MatchInnerinMatch.js:throw match.error;(thestatus === "error"branch, client side). - React's default
onCaughtErroralsoconsole.errors the route error from the routeCatchBoundary.
Expected
Hydrating an errored match renders the same error component the server rendered and does not throw, so there is no recoverable error and no console error. router.invalidate() (or the boundary reset) still re-runs the loader.
Root cause
packages/react-router/src/Match.tsx, MatchInner:
if (match.status === 'error') {
if (isServer ?? router.isServer) {
const RouteErrorComponent =
(route.options.errorComponent ?? router.options.defaultErrorComponent) || ErrorComponent
return (
<RouteErrorComponent error={match.error} reset={undefined} info={{ componentStack: '' }} />
)
}
throw match.error
}
The client path relies on CatchBoundary (only present when the route has an errorComponent) to render the error. For a match whose error was produced on the server and dehydrated, the throw happens while hydrating markup that already contains the error UI.
Proposed fix (patch we apply with pnpm patch)
Render the error component on the client as well, with a reset that invalidates the errored match and the same info as the server branch:
diff --git a/dist/cjs/Match.cjs b/dist/cjs/Match.cjs
index 0062da5e06271f1e25545979aa137b37e30ee295..0f13eb1cdd6bbdca38f2bbe9d348f91b4c694ddf 100644
--- a/dist/cjs/Match.cjs
+++ b/dist/cjs/Match.cjs
@@ -115,15 +115,14 @@ var MatchInner = react.memo(function MatchInnerImpl({ match }) {
}
if (match.status === "notFound") return require_renderRouteNotFound.renderRouteNotFound(router, route, match.error);
if (match.status === "error") {
- if (_tanstack_router_core_isServer.isServer ?? router.isServer) {
- const errorElement = /* @__PURE__ */ (0, react_jsx_runtime.jsx)((route.options.errorComponent ?? router.options.defaultErrorComponent) || require_CatchBoundary.ErrorComponent, {
- error: match.error,
- reset: void 0,
- info: { componentStack: "" }
- });
- return process.env.NODE_ENV !== "production" ? require_nonRouteComponentContext.wrapInNonRouteComponentContext(errorElement, "errorComponent") : errorElement;
- }
- throw match.error;
+ const errorElement = /* @__PURE__ */ (0, react_jsx_runtime.jsx)((route.options.errorComponent ?? router.options.defaultErrorComponent) || require_CatchBoundary.ErrorComponent, {
+ error: match.error,
+ reset: _tanstack_router_core_isServer.isServer ?? router.isServer ? void 0 : () => {
+ router.invalidate({ filter: (d) => d.id === match.id });
+ },
+ info: { componentStack: "" }
+ });
+ return process.env.NODE_ENV !== "production" ? require_nonRouteComponentContext.wrapInNonRouteComponentContext(errorElement, "errorComponent") : errorElement;
}
return out;
});
diff --git a/dist/esm/Match.js b/dist/esm/Match.js
index e275c3cb8c552f8adc91d18eecf28cad2412d117..4347395af384854fa048fd51fdd8098c8a959fbf 100644
--- a/dist/esm/Match.js
+++ b/dist/esm/Match.js
@@ -113,15 +113,14 @@ var MatchInner = React$1.memo(function MatchInnerImpl({ match }) {
}
if (match.status === "notFound") return renderRouteNotFound(router, route, match.error);
if (match.status === "error") {
- if (isServer ?? router.isServer) {
- const errorElement = /* @__PURE__ */ jsx((route.options.errorComponent ?? router.options.defaultErrorComponent) || ErrorComponent, {
- error: match.error,
- reset: void 0,
- info: { componentStack: "" }
- });
- return process.env.NODE_ENV !== "production" ? wrapInNonRouteComponentContext(errorElement, "errorComponent") : errorElement;
- }
- throw match.error;
+ const errorElement = /* @__PURE__ */ jsx((route.options.errorComponent ?? router.options.defaultErrorComponent) || ErrorComponent, {
+ error: match.error,
+ reset: isServer ?? router.isServer ? void 0 : () => {
+ router.invalidate({ filter: (d) => d.id === match.id });
+ },
+ info: { componentStack: "" }
+ });
+ return process.env.NODE_ENV !== "production" ? wrapInNonRouteComponentContext(errorElement, "errorComponent") : errorElement;
}
return out;
});
(The unified diff above is against the built dist/esm/Match.js and dist/cjs/Match.cjs; the equivalent source change is in MatchInner in src/Match.tsx: drop the throw match.error, build the element unconditionally, and pass reset: isServer ?? router.isServer ? undefined : () => router.invalidate({ filter: (d) => d.id === match.id }).)
Notes
- The repro is distilled from a vitest + jsdom harness that does an SSR render, loads the HTML as the document, and calls
hydrateRoot; it has the same shape as a production Hono SSR server plus a browser entry. Adjust the render helper (renderRouterToStream,renderRouterToString) to your setup. - With the patch the same harness reports no recoverable errors, no console errors, the error component is present after hydration, and a Retry button wired to
router.invalidate()clears the error and re-runs the loader.
Related: #8241 (the same server-inline / client-throw split in @tanstack/solid-router).
- Ngôn ngữ chính
- TypeScript
- Star
- 15.3k
- Fork
- 1.9k
- Merge trung bình
- 1 ngày 5 giờ
- Pull request đã merge (30 ngày)
- 46
Chuẩn bị môi trường
Khởi chạy dev container của dự án ngay trên trình duyệt, bằng tài khoản GitHub của bạn.
- Không có Dockerfile hay tệp Docker Compose
- Có mẫu pull request
- Đọc hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của TanStack/router
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 85/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Masked navigation drops the first character of the hash each time (__tempLocation hash missing '#')Có thể đã có người làm @hassanabrar202 đã nhận 8 ngày trước. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
Maintainer thường phản hồi trong vòng 1 ngày
-
router-generator: lazy-load Prettier (costs ~300–450ms per build even when formatting is off)Có thể đã có người làm @Sheraff đã nhận 27 ngày trước. Đang mởpackage: router-generator performance
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 85/100
Maintainer thường phản hồi trong vòng 1 ngày
-
router-generator: sibling `physical()` subtrees in a virtual route config generate duplicate identifiersCó thể đã có người làm @Sheraff đã nhận 27 ngày trước. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 76/100
Maintainer thường phản hồi trong vòng 1 ngày
-
docs(router): clarify static title fallback in SPA modeCó thể đã có người làm @Rohan-Dedhia đã nhận 18 ngày trước. Đang mở
Độ khó 1/5 1-3 giờ Mức phù hợp với người mới 62/100
Maintainer thường phản hồi trong vòng 1 ngày
Tất cả issue của TanStack/router
Issue tương tự
-
[BUG]: Shared links drop the configured basePath on GitHub PagesCó thể đã có người làm @anshulchikhale30-p đã nhận hôm nay. Đang mởbug
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 88/100
StabilityNexus/IdentityTokens-EVM-Frontend#182 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Add: GTrekkerĐang mởcheck:passed streams:add
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 72/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 70/100
Koenkk/zigbee-herdsman-converters#13900 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
area: ui Bug Payload OSS
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 88/100
payloadcms/payload#19839 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 88/100
jeanibarz/knowledge-base-mcp-server#1291 ·
Maintainer thường phản hồi trong vòng 1 ngày