Next.js生产环境API仅构建时运行及Plain Objects警告求助
问题:Next.js生产环境数据不更新+Server Action数据传递警告
一、生产环境地图无法显示新增养老院
开发模式下一切正常,但生产环境中,获取养老院数据的逻辑只在构建时运行,后续请求都返回旧数据,新增的养老院无法在地图上显示。
二、Server Action数据传递警告
改用Server Action获取数据后,出现以下警告:
Only plain objects can be passed to Client Components from Server Components. Objects with toJSON methods are not supported. Convert it manually to a simple value before passing it to props.
相关代码
_actions.js
export async function getCareHomes(){ try { await connectMongoDB(); const careHomes = await CareHome.find(); console.log('api/carehome careHomes: ',careHomes); // Return the list of care homes in the response return careHomes; } catch (error) { // Handle any errors that occur during the query console.error('Error:', error); // Return an error response return { message: 'Error fetching care homes' }; } }
CareHomeMap.jsx
'use client' import { useEffect, useState } from "react"; import { getCareHomes } from '../_actions' export default function CareHomeMap({ map, home }) { const [careHomeData, setCareHomeData] = useState(); useEffect(()=>{ try { getCareHomes().then(data =>{ setCareHomeData(data) }) // fetchCareHomes().then(data =>{ // setCareHomeData(data) // }) } catch (error) { console.log(error) } },[]) }
解决方法
针对问题1:生产环境数据不更新
原因
Next.js生产环境中,如果数据获取逻辑采用静态生成(Static Generation)模式,会在构建阶段预渲染所有数据,之后所有请求都会返回预渲染的静态内容,不会重新查询数据库获取新数据。
解决方案
- 强制动态渲染:在API路由或Server Action所在文件中添加配置,强制每次请求都实时查询数据库:
export const dynamic = 'force-dynamic'; - 增量静态再生(ISR):兼顾性能与数据新鲜度,设置缓存有效期,让Next.js定期重新生成静态内容:
export const revalidate = 60; // 每60秒重新生成一次,单位秒
针对问题2:Server Action数据传递警告
原因
CareHome.find()返回的是Mongoose文档对象,这类对象自带toJSON等内置方法,不属于普通JS对象,无法直接传递给客户端组件。
解决方案
将Mongoose文档转换成普通JS对象,两种方式任选:
- 查询时直接返回普通对象(推荐):
在find()后添加.lean(),Mongoose会直接返回无额外方法的普通对象:const careHomes = await CareHome.find().lean(); - 手动转换已获取的文档:
若需保留Mongoose转换逻辑,用toObject()逐个转换文档:return careHomes.map(home => home.toObject());
内容的提问来源于stack exchange,提问作者Niall
相关产品推荐
相关产品推荐

