Next.js中getStaticPaths is not a function错误排查求助
解决TypeError: getStaticPaths is not a function错误
问题根源
这个错误出现在Next.js静态生成(SSG)场景中,核心原因是:
- 动态路由页面(如
pages/posts/[id].tsx)使用了getStaticProps但未正确定义getStaticPaths函数 - 页面文件导出的
getStaticPaths不是合法异步函数,或存在语法错误 - 页面结构不符合Next.js静态生成规则,或误将组件逻辑和页面配置混淆
具体解决方案
方案1:改用客户端渲染(适配你的T3 Stack场景)
如果不需要预渲染页面,直接用客户端通过tRPC拉取数据即可,无需配置静态生成函数。修改你的动态路由页面文件(如pages/posts/[id].tsx):
import { useRouter } from 'next/router'; import { PostView } from '../../components/PostView'; export default function PostPage() { const router = useRouter(); const { id } = router.query; // 等待路由参数加载完成 if (!id) return null; return <PostView id={id as string} />; }
方案2:正确配置静态生成(SSG)
若需要预渲染页面,必须在动态路由页面中同时导出getStaticPaths和getStaticProps:
import { GetStaticPaths, GetStaticProps } from 'next'; import { prisma } from '../../server/db/client'; import { PostView } from '../../components/PostView'; export default function PostPage({ post }) { return <PostView id={post.id} />; } // 生成所有需要预渲染的文章路径 export const getStaticPaths: GetStaticPaths = async () => { const posts = await prisma.post.findMany({ select: { id: true } }); return { paths: posts.map(post => ({ params: { id: post.id } })), fallback: 'blocking', // 根据需求选true/false/blocking }; }; // 获取对应ID的文章数据 export const getStaticProps: GetStaticProps = async ({ params }) => { const post = await prisma.post.findUnique({ where: { id: params.id as string }, include: { Category: true, author: true }, }); if (!post) return { notFound: true }; return { props: { post }, revalidate: 60, // 可选,开启增量静态再生 }; };
额外排查要点
- 确认只有动态路由页面(带
[param]命名的文件)才使用getStaticPaths,普通页面无需配置 - 检查页面文件默认导出是否为React组件,
getStaticPaths是否为标准异步函数 - 验证数据库中文章ID的类型与tRPC接口接收的
postId类型一致(你的代码中为string) - 重启开发服务器,清除缓存后重新测试
内容的提问来源于stack exchange,提问作者Skyami
相关产品推荐
相关产品推荐

