You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js在Vercel构建时出现/blog/[slug]页面预渲染错误如何解决?

问题原因
  • 第一个核心原因是你项目开启了多语言(i18n)配置,但getStaticPaths生成路径时未携带locale参数:你代码中将locale相关配置注释了,构建时Vercel会为每个配置的locale生成对应页面路径,没有绑定locale的路径查询对应文章时会返回空结果,导致initialData[0]为undefined。
  • 第二个原因是getStaticProps没有做数据兜底校验:你直接将接口返回的initialData[0]作为article传给页面组件,一旦接口没有查询到对应slug的文章,article就是undefined,组件读取article.featured_image自然会抛出类型错误。
  • 另外你代码中revalidate参数存在语法错误,两个60之间缺失乘号,虽然不是本次报错的直接原因,但会导致构建语法报错。

本地运行正常是因为本地开发模式下fallback: true会触发按需渲染,不会预生成所有locale下的所有路径,仅在你访问对应路径时才查询数据,因此你访问默认locale下存在的文章路径不会触发问题,但Vercel构建阶段会预渲染所有你返回的paths对应的页面,就会触发错误。

解决方案
  1. 修复getStaticPaths的多语言路径生成逻辑,为每个文章对应每个locale生成独立路径:
export async function getStaticPaths({ locales }) {
  const articles = await fetchAPI(getArticles);
  const articlesData = await articles;

  const paths = articlesData.flatMap((article) => 
    locales.map(locale => ({
      params: { slug : article.slug },
      locale
    }))
  )

  return {
    paths,
    fallback: true
  };
}
  1. 在getStaticProps中添加数据校验逻辑,未查询到对应文章时返回404页面:
export async function getStaticProps({ params, locale }) {
  const res = await fetch(`${publicRuntimeConfig.API_URL}/articles?slug=${params.slug}`)
  let initialData = await res.json()
  // 新增校验逻辑
  if (!initialData || initialData.length === 0) {
    return {
      notFound: true
    }
  }
  const resBlog = await fetchAPI(getBlog)
  const dataBlog = await resBlog;

  return {
    props: {
      article: initialData[0],
      blogDescription: dataBlog.banner,
    },
    revalidate: 60 * 60 * 24 // 修复语法错误,补全乘号
  }
}
  1. 如果你的页面组件中还有直接读取article下属性的逻辑,建议也添加可选链操作符做兼容,比如把article.featured_image改成article?.featured_image,进一步避免空值报错。

内容的提问来源于stack exchange,提问作者taurOan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 01:15:08