使用Next.js+Sanity构建作品集时生产构建报错求助
Next.js + Sanity 生产构建失败问题解决
从错误截图来看,核心报错为:
Error: Error serializing
.experiencereturned fromgetStaticPropsin "/".
Reason:undefinedcannot be serialized as JSON. Please usenullor 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
相关产品推荐
相关产品推荐

