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

使用Next.js+Sanity构建作品集时生产构建报错求助

Next.js + Sanity 生产构建失败问题解决

从错误截图来看,核心报错为:

Error: Error serializing .experience returned from getStaticProps in "/".
Reason: undefined cannot be serialized as JSON. Please use null or omit this value.

这是Next.js生产构建的典型问题:getStaticProps返回的数据中包含不可序列化内容(如undefined、函数、循环引用对象),无法转换为JSON传递给页面组件。

排查与解决步骤

  • 检查Sanity查询返回的数据
    在getStaticProps中临时打印数据,确认experience数组里的字段是否存在undefined值:

    export async function getStaticProps() {
      const experience = await sanityClient.fetch(/* 你的GROQ查询语句 */);
      console.log('Experience Data:', experience); // 本地运行后查看终端输出
      return { props: { experience } };
    }
    

    如果查询结果里有undefined字段,修改GROQ查询,用coalesce函数给字段设置默认值(比如null):

    *[_type == "experience"] {
      title,
      company,
      description: coalesce(description, null), // 给可能为空的字段设置默认值
      date
    }
    
  • 手动过滤/序列化数据
    如果查询返回了非JSON兼容的内容(比如Sanity的_raw开头的字段),手动过滤后再返回:

    export async function getStaticProps() {
      const experience = await sanityClient.fetch(/* 你的GROQ查询 */);
      // 替换undefined为null,过滤不可序列化字段
      const serializableData = experience.map(item => ({
        ...item,
        description: item.description ?? null
      }));
      return { props: { experience: serializableData } };
    }
    
  • 验证依赖版本兼容性
    确认next和next-sanity版本适配,避免因版本不匹配导致的数据处理异常。查看package.json,建议使用官方推荐的兼容版本:

    {
      "dependencies": {
        "next": "^14.0.0",
        "next-sanity": "^7.0.0"
      }
    }
    
  • 临时关闭严格模式调试
    如果开发环境正常但生产构建报错,可临时在next.config.js中关闭React严格模式排查问题(不建议长期使用):

    const nextConfig = {
      reactStrictMode: false,
    };
    module.exports = nextConfig;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 15:17:38