错误:dynamic() 中的 'ssr: false' 选项在服务端组件中不受支持。请仅在客户端组件中使用带有 'ssr: false' 的 dynamic()。
Error: 'ssr: false' option in dynamic() is not supported in Server Components. Use dynamic() with 'ssr: false' only in Client Components.
ID: nextjs/dynamic-import-ssr-false-client-component
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Next.js 14.x | active | — | — | — |
| Next.js 15.x | active | — | — | — |
根因分析
在服务端组件中使用了带有 { ssr: false } 的 dynamic() 导入,但此选项仅在客户端组件中有效,因为服务端组件总是在服务端渲染。
English
The dynamic() import with { ssr: false } is used in a Server Component, but this option only works within Client Components because Server Components always render on the server.
官方文档
https://nextjs.org/docs/app/api-reference/functions/dynamic解决方案
-
通过在文件顶部添加 'use client' 将 dynamic() 导入移到客户端组件中。示例:'use client'; import dynamic from 'next/dynamic'; const MyComponent = dynamic(() => import('./MyComponent'), { ssr: false }); -
如果无法将父组件转换为客户端组件,请创建一个单独的包装器客户端组件来处理 dynamic 导入,然后在服务端组件中导入该包装器。
-
使用不带 ssr: false 的 next/dynamic,而是在 useEffect 中使用 mounted 状态检查来处理浏览器专用代码。
无效尝试
常见但无效的做法:
-
60% 失败
The component may rely on browser-only APIs (window, document, etc.) that will crash during server-side rendering. Removing 'ssr: false' without client isolation will cause ReferenceError.
-
100% 失败
This is a build-time validation error that occurs before runtime. The framework throws it during module resolution, so try-catch cannot intercept it.
-
80% 失败
Server Components do not have access to the window object, and conditional imports in Server Components still attempt to resolve the module during server-side rendering, leading to the same error or different import failures.