not-found-and-errors
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNot Found and Errors
未找到与错误处理
TanStack Router handles two categories of "not found": unmatched URL paths (automatic) and missing resources like a post that doesn't exist (manual via ). Error boundaries are configured per-route via .
notFound()errorComponentCRITICAL: Do NOT use the deprecated. When present,NotFoundRouteandnotFound()will NOT work. Remove it and usenotFoundComponentinstead. CRITICAL:notFoundComponentmay be undefined insideuseLoaderData. UsenotFoundComponent,useParams, oruseSearchinstead.useRouteContext
TanStack Router 处理两类“未找到(not found)”场景:未匹配的 URL 路径(自动触发)和缺失的资源(例如不存在的文章,通过 手动触发)。错误边界通过 按路由配置。
notFound()errorComponent关键提示:请勿使用已废弃的。如果存在该配置,NotFoundRoute和notFound()将无法生效。请移除它并改用notFoundComponent。 关键提示:在notFoundComponent中,notFoundComponent的返回值可能为 undefined。请改用useLoaderData、useParams或useSearch。useRouteContext
Not Found Handling
未找到处理
Global 404: notFoundComponent
on Root Route
notFoundComponent全局 404:根路由的 notFoundComponent
notFoundComponenttsx
// src/routes/__root.tsx
import { createRootRoute, Outlet, Link } from '@tanstack/react-router'
export const Route = createRootRoute({
component: () => <Outlet />,
notFoundComponent: () => {
return (
<div>
<h1>404 — Page Not Found</h1>
<Link to="/">Go Home</Link>
</div>
)
},
})tsx
// src/routes/__root.tsx
import { createRootRoute, Outlet, Link } from '@tanstack/react-router'
export const Route = createRootRoute({
component: () => <Outlet />,
notFoundComponent: () => {
return (
<div>
<h1>404 — Page Not Found</h1>
<Link to="/">Go Home</Link>
</div>
)
},
})Router-Wide Default: defaultNotFoundComponent
defaultNotFoundComponent路由级默认配置:defaultNotFoundComponent
defaultNotFoundComponenttsx
// src/router.tsx
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
const router = createRouter({
routeTree,
defaultNotFoundComponent: () => {
return (
<div>
<p>Not found!</p>
<Link to="/">Go home</Link>
</div>
)
},
})tsx
// src/router.tsx
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
const router = createRouter({
routeTree,
defaultNotFoundComponent: () => {
return (
<div>
<p>Not found!</p>
<Link to="/">Go home</Link>
</div>
)
},
})Per-Route 404: Missing Resources with notFound()
notFound()单路由 404:通过 notFound()
处理资源缺失
notFound()Throw in or when a resource doesn't exist. It works like — throw it to trigger the not-found boundary.
notFound()loaderbeforeLoadredirect()tsx
// src/routes/posts.$postId.tsx
import { createFileRoute, notFound } from '@tanstack/react-router'
import { getPost } from '../api'
export const Route = createFileRoute('/posts/$postId')({
loader: async ({ params: { postId } }) => {
const post = await getPost(postId)
if (!post) throw notFound()
return { post }
},
component: PostComponent,
notFoundComponent: ({ data }) => {
const { postId } = Route.useParams()
return <p>Post "{postId}" not found</p>
},
})
function PostComponent() {
const { post } = Route.useLoaderData()
return <h1>{post.title}</h1>
}当资源不存在时,在 或 中抛出 。它的工作方式类似 ——抛出后会触发未找到边界(not-found boundary)。
loaderbeforeLoadnotFound()redirect()tsx
// src/routes/posts.$postId.tsx
import { createFileRoute, notFound } from '@tanstack/react-router'
import { getPost } from '../api'
export const Route = createFileRoute('/posts/$postId')({
loader: async ({ params: { postId } }) => {
const post = await getPost(postId)
if (!post) throw notFound()
return { post }
},
component: PostComponent,
notFoundComponent: ({ data }) => {
const { postId } = Route.useParams()
return <p>Post "{postId}" not found</p>
},
})
function PostComponent() {
const { post } = Route.useLoaderData()
return <h1>{post.title}</h1>
}Targeting a Specific Route with notFound({ routeId })
notFound({ routeId })通过 notFound({ routeId })
指定处理未找到错误的路由
notFound({ routeId })You can force a specific parent route to handle the not-found error:
tsx
// src/routes/_layout/posts.$postId.tsx
import { createFileRoute, notFound } from '@tanstack/react-router'
export const Route = createFileRoute('/_layout/posts/$postId')({
loader: async ({ params: { postId } }) => {
const post = await getPost(postId)
if (!post) throw notFound({ routeId: '/_layout' })
return { post }
},
})你可以强制指定某个父路由来处理未找到错误:
tsx
// src/routes/_layout/posts.$postId.tsx
import { createFileRoute, notFound } from '@tanstack/react-router'
export const Route = createFileRoute('/_layout/posts/$postId')({
loader: async ({ params: { postId } }) => {
const post = await getPost(postId)
if (!post) throw notFound({ routeId: '/_layout' })
return { post }
},
})Targeting Root Route with rootRouteId
rootRouteId通过 rootRouteId
指定根路由
rootRouteIdtsx
import { createFileRoute, notFound, rootRouteId } from '@tanstack/react-router'
export const Route = createFileRoute('/posts/$postId')({
loader: async ({ params: { postId } }) => {
const post = await getPost(postId)
if (!post) throw notFound({ routeId: rootRouteId })
return { post }
},
})tsx
import { createFileRoute, notFound, rootRouteId } from '@tanstack/react-router'
export const Route = createFileRoute('/posts/$postId')({
loader: async ({ params: { postId } }) => {
const post = await getPost(postId)
if (!post) throw notFound({ routeId: rootRouteId })
return { post }
},
})notFoundMode
: Fuzzy vs Root
notFoundModenotFoundMode
:Fuzzy 模式与 Root 模式
notFoundModefuzzy
(default)
fuzzyfuzzy
(默认)
fuzzyThe router finds the nearest parent route with children and a . Preserves as much parent layout as possible.
notFoundComponentGiven routes: → → , accessing :
__root__posts$postId/posts/1/edit- renders
<Root> - renders
<Posts> - renders (nearest parent with children + notFoundComponent)
<Posts.notFoundComponent>
路由会查找最近的、拥有子路由且配置了 的父路由,尽可能保留父级布局。
notFoundComponent假设有路由层级: → → ,访问 时:
__root__posts$postId/posts/1/edit- 渲染
<Root> - 渲染
<Posts> - 渲染(最近的拥有子路由和
<Posts.notFoundComponent>的父路由)notFoundComponent
root
rootroot
rootAll not-found errors go to the root route's , regardless of matching:
notFoundComponenttsx
const router = createRouter({
routeTree,
notFoundMode: 'root',
})所有未找到错误都会交由根路由的 处理,无论匹配情况如何:
notFoundComponenttsx
const router = createRouter({
routeTree,
notFoundMode: 'root',
})Error Handling
错误处理
errorComponent
Per Route
errorComponent单路由 errorComponent
errorComponenterrorComponenterrorinforesetrouter.invalidate()tsx
// src/routes/posts.$postId.tsx
import { createFileRoute, useRouter } from '@tanstack/react-router'
export const Route = createFileRoute('/posts/$postId')({
loader: async ({ params: { postId } }) => {
const res = await fetch(`/api/posts/${postId}`)
if (!res.ok) throw new Error('Failed to load post')
return res.json()
},
component: PostComponent,
errorComponent: PostErrorComponent,
})
function PostErrorComponent({
error,
}: {
error: unknown
info?: { componentStack: string }
reset: () => void
}) {
const router = useRouter()
return (
<div>
<p>Error: {error instanceof Error ? error.message : String(error)}</p>
<button
onClick={() => {
// Invalidate re-runs the loader and resets the error boundary
router.invalidate()
}}
>
Retry
</button>
</div>
)
}
function PostComponent() {
const data = Route.useLoaderData()
return <h1>{data.title}</h1>
}errorComponenterrorinforesetrouter.invalidate()tsx
// src/routes/posts.$postId.tsx
import { createFileRoute, useRouter } from '@tanstack/react-router'
export const Route = createFileRoute('/posts/$postId')({
loader: async ({ params: { postId } }) => {
const res = await fetch(`/api/posts/${postId}`)
if (!res.ok) throw new Error('Failed to load post')
return res.json()
},
component: PostComponent,
errorComponent: PostErrorComponent,
})
function PostErrorComponent({
error,
}: {
error: unknown
info?: { componentStack: string }
reset: () => void
}) {
const router = useRouter()
return (
<div>
<p>Error: {error instanceof Error ? error.message : String(error)}</p>
<button
onClick={() => {
// Invalidate re-runs the loader and resets the error boundary
router.invalidate()
}}
>
Retry
</button>
</div>
)
}
function PostComponent() {
const data = Route.useLoaderData()
return <h1>{data.title}</h1>
}Router-Wide Default Error Component
路由级默认错误组件
tsx
const router = createRouter({
routeTree,
defaultErrorComponent: ({ error }) => {
const router = useRouter()
return (
<div>
<p>
Something went wrong:{' '}
{error instanceof Error ? error.message : String(error)}
</p>
<button
onClick={() => {
router.invalidate()
}}
>
Retry
</button>
</div>
)
},
})tsx
const router = createRouter({
routeTree,
defaultErrorComponent: ({ error }) => {
const router = useRouter()
return (
<div>
<p>
Something went wrong:{' '}
{error instanceof Error ? error.message : String(error)}
</p>
<button
onClick={() => {
router.invalidate()
}}
>
Retry
</button>
</div>
)
},
})Data in notFoundComponent
notFoundComponentnotFoundComponent
中的数据
notFoundComponentnotFoundComponentuseLoaderDatatsx
notFoundComponent: ({ data }) => {
// SAFE — always available:
const params = Route.useParams()
const search = Route.useSearch()
const context = Route.useRouteContext()
// UNSAFE — may be undefined:
// const loaderData = Route.useLoaderData()
return <p>Item {params.id} not found</p>
}To forward partial data, use the option on :
datanotFound()tsx
loader: async ({ params }) => {
const partialData = await getPartialData(params.id)
if (!partialData.fullResource) {
throw notFound({ data: { name: partialData.name } })
}
return partialData
},
notFoundComponent: ({ data }) => {
// data is typed as unknown — validate it
const info = data as { name: string } | undefined
return <p>{info?.name ?? 'Resource'} not found</p>
},notFoundComponentuseLoaderDatatsx
notFoundComponent: ({ data }) => {
// SAFE — always available:
const params = Route.useParams()
const search = Route.useSearch()
const context = Route.useRouteContext()
// UNSAFE — may be undefined:
// const loaderData = Route.useLoaderData()
return <p>Item {params.id} not found</p>
}如需传递部分数据,可使用 的 选项:
notFound()datatsx
loader: async ({ params }) => {
const partialData = await getPartialData(params.id)
if (!partialData.fullResource) {
throw notFound({ data: { name: partialData.name } })
}
return partialData
},
notFoundComponent: ({ data }) => {
// data is typed as unknown — validate it
const info = data as { name: string } | undefined
return <p>{info?.name ?? 'Resource'} not found</p>
},Route Masking
路由掩码(Route Masking)
Route masking shows a different URL in the browser bar than the actual route being rendered. Masking data is stored in and is lost when the URL is shared or opened in a new tab.
location.state路由掩码会在浏览器地址栏显示与实际渲染路由不同的 URL。掩码数据存储在 中,当 URL 被分享或在新标签页打开时会丢失。
location.stateImperative Masking on <Link>
<Link>在 <Link>
上使用命令式掩码
<Link>tsx
import { Link } from '@tanstack/react-router'
function PhotoGrid({ photoId }: { photoId: string }) {
return (
<Link
to="/photos/$photoId/modal"
params={{ photoId }}
mask={{
to: '/photos/$photoId',
params: { photoId },
}}
>
Open Photo
</Link>
)
}tsx
import { Link } from '@tanstack/react-router'
function PhotoGrid({ photoId }: { photoId: string }) {
return (
<Link
to="/photos/$photoId/modal"
params={{ photoId }}
mask={{
to: '/photos/$photoId',
params: { photoId },
}}
>
Open Photo
</Link>
)
}Imperative Masking with useNavigate
useNavigate使用 useNavigate
实现命令式掩码
useNavigatetsx
import { useNavigate } from '@tanstack/react-router'
function OpenPhotoButton({ photoId }: { photoId: string }) {
const navigate = useNavigate()
return (
<button
onClick={() =>
navigate({
to: '/photos/$photoId/modal',
params: { photoId },
mask: {
to: '/photos/$photoId',
params: { photoId },
},
})
}
>
Open Photo
</button>
)
}tsx
import { useNavigate } from '@tanstack/react-router'
function OpenPhotoButton({ photoId }: { photoId: string }) {
const navigate = useNavigate()
return (
<button
onClick={() =>
navigate({
to: '/photos/$photoId/modal',
params: { photoId },
mask: {
to: '/photos/$photoId',
params: { photoId },
},
})
}
>
Open Photo
</button>
)
}Declarative Masking with createRouteMask
createRouteMask使用 createRouteMask
实现声明式掩码
createRouteMasktsx
import { createRouter, createRouteMask } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
const photoModalMask = createRouteMask({
routeTree,
from: '/photos/$photoId/modal',
to: '/photos/$photoId',
params: (prev) => ({ photoId: prev.photoId }),
})
const router = createRouter({
routeTree,
routeMasks: [photoModalMask],
})tsx
import { createRouter, createRouteMask } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
const photoModalMask = createRouteMask({
routeTree,
from: '/photos/$photoId/modal',
to: '/photos/$photoId',
params: (prev) => ({ photoId: prev.photoId }),
})
const router = createRouter({
routeTree,
routeMasks: [photoModalMask],
})Unmasking on Reload
页面重载时解除掩码
By default, masks survive local page reloads. To unmask on reload:
tsx
// Per-mask
const mask = createRouteMask({
routeTree,
from: '/photos/$photoId/modal',
to: '/photos/$photoId',
params: (prev) => ({ photoId: prev.photoId }),
unmaskOnReload: true,
})
// Per-link
<Link
to="/photos/$photoId/modal"
params={{ photoId }}
mask={{ to: '/photos/$photoId', params: { photoId } }}
unmaskOnReload
>
Open Photo
</Link>
// Router-wide default
const router = createRouter({
routeTree,
unmaskOnReload: true,
})默认情况下,掩码在本地页面重载时仍然有效。如需在重载时解除掩码:
tsx
// Per-mask
const mask = createRouteMask({
routeTree,
from: '/photos/$photoId/modal',
to: '/photos/$photoId',
params: (prev) => ({ photoId: prev.photoId }),
unmaskOnReload: true,
})
// Per-link
<Link
to="/photos/$photoId/modal"
params={{ photoId }}
mask={{ to: '/photos/$photoId', params: { photoId } }}
unmaskOnReload
>
Open Photo
</Link>
// Router-wide default
const router = createRouter({
routeTree,
unmaskOnReload: true,
})Common Mistakes
常见错误
1. HIGH: Using deprecated NotFoundRoute
NotFoundRoute1. 高优先级:使用已废弃的 NotFoundRoute
NotFoundRoutetsx
// WRONG — NotFoundRoute blocks notFound() and notFoundComponent from working
import { NotFoundRoute } from '@tanstack/react-router'
const notFoundRoute = new NotFoundRoute({ component: () => <p>404</p> })
const router = createRouter({ routeTree, notFoundRoute })
// CORRECT — use notFoundComponent on root route
export const Route = createRootRoute({
component: () => <Outlet />,
notFoundComponent: () => <p>404</p>,
})tsx
// WRONG — NotFoundRoute blocks notFound() and notFoundComponent from working
import { NotFoundRoute } from '@tanstack/react-router'
const notFoundRoute = new NotFoundRoute({ component: () => <p>404</p> })
const router = createRouter({ routeTree, notFoundRoute })
// CORRECT — use notFoundComponent on root route
export const Route = createRootRoute({
component: () => <Outlet />,
notFoundComponent: () => <p>404</p>,
})2. MEDIUM: Expecting useLoaderData
in notFoundComponent
useLoaderDatanotFoundComponent2. 中优先级:在 notFoundComponent
中使用 useLoaderData
notFoundComponentuseLoaderDatatsx
// WRONG — loader may not have completed
notFoundComponent: () => {
const data = Route.useLoaderData() // may be undefined!
return <p>{data.title} not found</p>
}
// CORRECT — use safe hooks
notFoundComponent: () => {
const { postId } = Route.useParams()
return <p>Post {postId} not found</p>
}tsx
// WRONG — loader may not have completed
notFoundComponent: () => {
const data = Route.useLoaderData() // may be undefined!
return <p>{data.title} not found</p>
}
// CORRECT — use safe hooks
notFoundComponent: () => {
const { postId } = Route.useParams()
return <p>Post {postId} not found</p>
}3. MEDIUM: Leaf routes cannot handle not-found errors
3. 中优先级:叶子路由无法处理未找到错误
Only routes with children (and therefore an ) can render . Leaf routes (routes without children) will never catch not-found errors — the error bubbles up to the nearest parent with children.
<Outlet>notFoundComponenttsx
// This route has NO children — notFoundComponent here will not catch
// unmatched child paths (there are no child paths to unmatch)
export const Route = createFileRoute('/posts/$postId')({
// notFoundComponent here only works for notFound() thrown in THIS route's loader
// It does NOT catch path-based not-founds
notFoundComponent: () => <p>Not found</p>,
})只有拥有子路由的路由(因此会渲染 )才能渲染 。叶子路由(没有子路由的路由)永远不会捕获未找到错误——错误会冒泡到最近的有子路由的父路由。
<Outlet>notFoundComponenttsx
// This route has NO children — notFoundComponent here will not catch
// unmatched child paths (there are no child paths to unmatch)
export const Route = createFileRoute('/posts/$postId')({
// notFoundComponent here only works for notFound() thrown in THIS route's loader
// It does NOT catch path-based not-founds
notFoundComponent: () => <p>Not found</p>,
})4. MEDIUM: Expecting masked URLs to survive sharing
4. 中优先级:认为掩码后的 URL 可以在分享后保持有效
Masking data lives in (browser history). When a masked URL is copied, shared, or opened in a new tab, the masking data is lost. The browser navigates to the visible (masked) URL directly.
location.state掩码数据存储在 (浏览器历史记录)中。当掩码后的 URL 被复制、分享或在新标签页打开时,掩码数据会丢失,浏览器会直接导航到可见的(掩码后的)URL。
location.state5. HIGH (cross-skill): Using reset()
alone instead of router.invalidate()
reset()router.invalidate()5. 高优先级(跨技能):仅使用 reset()
而不使用 router.invalidate()
reset()router.invalidate()tsx
// WRONG — reset() clears the error boundary but does NOT re-run the loader
function ErrorFallback({
error,
reset,
}: {
error: unknown
reset: () => void
}) {
return <button onClick={reset}>Retry</button>
}
// CORRECT — invalidate re-runs loaders and resets the error boundary
function ErrorFallback({ error }: { error: unknown; reset: () => void }) {
const router = useRouter()
return (
<button
onClick={() => {
router.invalidate()
}}
>
Retry
</button>
)
}tsx
// WRONG — reset() clears the error boundary but does NOT re-run the loader
function ErrorFallback({
error,
reset,
}: {
error: unknown
reset: () => void
}) {
return <button onClick={reset}>Retry</button>
}
// CORRECT — invalidate re-runs loaders and resets the error boundary
function ErrorFallback({ error }: { error: unknown; reset: () => void }) {
const router = useRouter()
return (
<button
onClick={() => {
router.invalidate()
}}
>
Retry
</button>
)
}Cross-References
交叉参考
- router-core/data-loading — thrown in loaders interacts with error boundaries and loader data availability.
notFound()retry requireserrorComponent.router.invalidate() - router-core/type-safety — data is typed as
notFoundComponent; validate before use.unknown
- router-core/data-loading — 在 loader 中抛出的 会与错误边界和 loader 数据可用性产生交互。
notFound()的重试功能需要使用errorComponent。router.invalidate() - router-core/type-safety — 的数据类型为
notFoundComponent,使用前请进行校验。unknown