TanStack Router手动抛出notFound()时自定义notFoundComponent不显示
问题
我为网站主页配置了如下路由:
export const Route = createFileRoute("/")({ component: HomePage, beforeLoad: async () => { try { const missionState = await getMissionState(); return { missionState }; } catch (error) { console.error("Couldn't fetch mission state from server", error); throw notFound(); } }, loader: async ({ context: { missionState } }) => { if (missionState === MissionStateEnum.NOT_STARTED) { return { id: undefined, state: missionState, start_epoch_ms: undefined, robots_id: undefined, } as Mission; } const res = await getCurrentMission(); console.log(res); return res; }, notFoundComponent: NotLoadedStatePage, });
自定义错误组件如下:
const NotLoadedStatePage = () => { console.log("NotLoadedStatePage"); return ( <div className="flex flex-col h-full items-center justify-between m-5"> <PageMainHeader title={websiteText.serverError} /> <div className="text-2xl font-semibold text-primary"> Couldn't fetch mission state from server, please check the server's status or try again later. </div> <SignatureText /> </div> ); };
但关闭服务器访问页面时,却显示默认的NotFound页面,控制台提示:
Warning: A notFoundError was encountered on the route with ID "__root__", but a notFoundComponent option was not configured, nor was a router level defaultNotFoundComponent configured. Consider configuring at least one of these to avoid TanStack Router's overly generic defaultNotFoundComponent (<div>Not Found<div>)
解决方案
问题核心是**beforeLoad阶段抛出的notFound错误会冒泡到顶层的__root__路由**,你仅在/路由配置了notFoundComponent,但__root__路由未配置对应错误组件,因此触发了全局默认页面。可通过以下方式修复:
方式一:为__root__路由配置错误组件
找到项目中的__root__路由文件(通常路径为app/__root__.tsx),添加notFoundComponent配置:
export const Route = createFileRoute("__root__")({ component: App, notFoundComponent: NotLoadedStatePage, });
方式二:设置全局默认错误组件
在创建Router实例的代码文件(如router.tsx)中,添加defaultNotFoundComponent参数:
const router = createRouter({ routeTree: routeTree, defaultNotFoundComponent: NotLoadedStatePage, });
可选优化:调整错误处理逻辑(不依赖notFound机制)
若不想依赖路由的notFound机制,可修改beforeLoad逻辑,返回错误状态而非抛出错误,在组件内判断并渲染错误页面:
- 修改
beforeLoad:
beforeLoad: async () => { try { const missionState = await getMissionState(); return { missionState, error: null }; } catch (error) { console.error("Couldn't fetch mission state from server", error); return { missionState: null, error }; } },
- 在
HomePage组件中判断状态:
const HomePage = () => { const { missionState, error } = useRouteContext(); if (error) { return <NotLoadedStatePage />; } // 原主页渲染逻辑 return <div>主页内容</div>; };
内容的提问来源于stack exchange,提问作者FlyingFish
相关产品推荐
相关产品推荐

