NextJS App Router中notFound()失效,404页面显示空白问题求助
排查Next.js App Router中notFound()触发后页面空白报错的问题
以下是几个常见问题点及对应解决方法:
确保页面为服务器组件
检查app/[slug]/page.tsx顶部是否存在'use client'指令。notFound()是服务器端专属API,仅能在服务器组件中调用,客户端组件中调用会直接报错导致页面空白。若有该指令,直接移除(若需客户端交互,可将数据获取逻辑拆分到父级服务器组件中,由父组件触发notFound)。规范notFound()的调用位置
notFound()必须在服务器组件的顶层作用域或async数据获取函数中调用,禁止在useEffect等客户端钩子、事件处理函数或渲染分支的异步逻辑里调用。正确示例:import { notFound } from 'next/navigation'; import { groq } from 'next-sanity'; import { sanityClient } from '@/lib/sanity'; export default async function Page({ params }: { params: { slug: string } }) { const post = await sanityClient.fetch( groq`*[_type == "post" && slug.current == $slug][0]`, { slug: params.slug } ); if (!post) { notFound(); } return ( <div> <h1>{post.title}</h1> {/* 页面内容 */} </div> ); }避免捕获notFound()抛出的错误
如果数据查询逻辑被try/catch包裹,不要捕获notFound()抛出的NotFoundError,否则会阻止Next.js自动渲染404页面。若需处理其他错误,可在catch分支中判断错误类型后重新抛出:import { notFound, NotFoundError } from 'next/navigation'; // ... try { const post = await sanityClient.fetch(query, { slug: params.slug }); if (!post) { notFound(); } } catch (error) { if (error instanceof NotFoundError) { throw error; } console.error('数据查询失败:', error); notFound(); }核对Next.js版本与路由模式
确认使用的是Next.js 13+的App Router模式,notFound()是App Router专属API;若为Pages Router项目,需改用return { notFound: true }的逻辑。重启开发服务器
开发环境可能存在缓存问题导致notFound逻辑未生效,尝试关闭并重启next dev服务,同时清除浏览器缓存后再测试。
内容的提问来源于stack exchange,提问作者Baljka Gan
相关产品推荐
相关产品推荐

