我正在开发一个 Next JS 项目,我已将其部署到 Vercel 上,一开始它工作得很好,这就是为什么我很长时间没有检查网站状态,只是在本地开发并推送到 GitHub 的原因。现在突然我检查它并收到此错误。
ReferenceError: document is not defined
at t.exports.r.INSERT (/vercel/path0/.next/server/app/dashboard/create/page.js:1:160188)
at r (/vercel/path0/.next/server/app/dashboard/create/page.js:1:27485)
at t.exports.Object.defineProperty.value (/vercel/path0/.next/server/app/dashboard/create/page.js:1:43298)
at r (/vercel/path0/.next/server/app/dashboard/create/page.js:1:27485)
at t.exports.Object.defineProperty.value (/vercel/path0/.next/server/app/dashboard/create/page.js:1:125932)
at r (/vercel/path0/.next/server/app/dashboard/create/page.js:1:27485)
at t.exports.Object.defineProperty.value (/vercel/path0/.next/server/app/dashboard/create/page.js:1:196459)
at r (/vercel/path0/.next/server/app/dashboard/create/page.js:1:27485)
at Object.<anonymous> (/vercel/path0/.next/server/app/dashboard/create/page.js:1:239478)
at r (/vercel/path0/.next/server/app/dashboard/create/page.js:1:27485)
Error occurred prerendering page "/dashboard/create". Read more: https://nextjs.org/docs/messages/prerender-error
ReferenceError: document is not defined
at t.exports.r.INSERT (/vercel/path0/.next/server/app/dashboard/create/page.js:1:160188)
at r (/vercel/path0/.next/server/app/dashboard/create/page.js:1:27485)
at t.exports.Object.defineProperty.value (/vercel/path0/.next/server/app/dashboard/create/page.js:1:43298)
at r (/vercel/path0/.next/server/app/dashboard/create/page.js:1:27485)
at t.exports.Object.defineProperty.value (/vercel/path0/.next/server/app/dashboard/create/page.js:1:125932)
at r (/vercel/path0/.next/server/app/dashboard/create/page.js:1:27485)
at t.exports.Object.defineProperty.value (/vercel/path0/.next/server/app/dashboard/create/page.js:1:196459)
at r (/vercel/path0/.next/server/app/dashboard/create/page.js:1:27485)
at Object.<anonymous> (/vercel/path0/.next/server/app/dashboard/create/page.js:1:239478)
at r (/vercel/path0/.next/server/app/dashboard/create/page.js:1:27485)
我尝试阅读此内容,发现此目录有问题
/app/dashboard/page.js
我确信我没有使用该特定文件的文档。但我使用 Navbar.jsx 文件中的文档。这是代码
const [toggle_icon, set_toggle_icon] = useState(faBarsStaggered);
useEffect(() => {
if (toggle_icon == faBarsStaggered) {
menuRef.current.style.left = "-110%"
document.body.style.overflowY = 'scroll'
} else {
menuRef.current.style.left = "0"
document.body.style.overflowY = 'hidden'
}
}, [toggle_icon])
我使用该代码来设置菜单打开时隐藏的正文溢出。 现在我不知道是什么导致了错误。请帮助我。 如果您需要任何其他信息来了解有关该错误的更多信息,请告诉我。
出现
ReferenceError: document is not defined
是因为您的代码是在 SSR(即服务器端渲染)中执行的,其中没有 DOM。但代码依赖于 DOM。因此,代码在 SSR 期间尝试访问文档对象,但由于没有 DOM 而找不到它。这就是您收到此错误的原因。
要解决此错误,您需要在发生错误的文件顶部添加
"use client"
。