错误:调用了 notFound(),但最近的错误边界是客户端组件。notFound() 必须在服务器组件或服务器端函数中调用。
Error: notFound() was called but the nearest error boundary is a client component. notFound() must be called within a server component or a server-side function.
ID: nextjs/not-found-in-client-component
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 14.2.0 | active | — | — | — |
| 15.0.0 | active | — | — | — |
根因分析
从 'next/navigation' 调用的 notFound() 函数在客户端组件或缺乏服务器端请求处理管道的上下文中被调用,导致错误边界是客户端组件而非服务器端的 not-found 页面。
English
The notFound() function from 'next/navigation' is invoked inside a Client Component or a context that lacks access to the server-side request handling pipeline, causing the error boundary to be a client-side component instead of the server-side not-found page.
官方文档
https://nextjs.org/docs/app/api-reference/functions/not-found解决方案
-
Move the notFound() call to a Server Component that wraps the Client Component. Pass a prop (e.g., notFound flag) from the server to the client.
-
If you must trigger not-found from a Client Component, use a server action that returns a redirect to the not-found page, or use the error.js file pattern with notFound() in the parent layout.
无效尝试
常见但无效的做法:
-
Wrapping the Client Component in a try-catch to catch notFound()
90% 失败
notFound() throws a special NEXT_NOT_FOUND error that cannot be caught by regular try-catch blocks. It must be handled by the Next.js routing layer.
-
Importing notFound from 'next/client' (which doesn't exist)
100% 失败
There is no 'next/client' module. The function only exists in 'next/navigation' and its behavior is server-side only.
-
Using notFound() inside a useEffect
95% 失败
notFound() is meant for synchronous server-side execution. Calling it asynchronously in useEffect doesn't trigger the server-side not-found page.