nextjs module_error ai_generated true

错误:此模块无法从服务器组件模块中导入。它只能从客户端组件中使用。

Error: This module cannot be imported from a Server Component module. It should only be used from a Client Component.

ID: nextjs/server-component-import-client-side-only-module

其他格式: JSON · Markdown 中文 · English
90%修复率
87%置信度
1证据数
2023-05-10首次发现

版本兼容性

版本状态引入弃用备注
Next.js 13.4.0 active
Next.js 14.0.0 active
Next.js 14.2.0 active

根因分析

一个使用浏览器专用 API(如 window, document)或在模块级别标记了 'use client' 的模块被导入到服务器组件中,而服务器组件在服务器上运行,这些 API 不存在。

English

A module that uses browser-only APIs (e.g., window, document) or is marked with 'use client' at the module level is imported into a Server Component, which runs on the server where those APIs don't exist.

generic

官方文档

https://nextjs.org/docs/app/building-your-application/rendering/server-components#third-party-packages

解决方案

  1. Use dynamic import with ssr: false to load the module only on the client: 'const MyComponent = dynamic(() => import('./MyClientComponent'), { ssr: false })'.
  2. Create a wrapper Client Component that imports the module and pass props from the Server Component.
  3. If the module is small, refactor it to avoid browser APIs and make it usable on the server.

无效尝试

常见但无效的做法:

  1. 60% 失败

    This converts the entire Server Component to a Client Component, losing server-side benefits and potentially causing other issues.

  2. 70% 失败

    The module may still use browser APIs internally; removing the directive doesn't make the code run on the server.

  3. 80% 失败

    Dynamic import alone still runs on the server during SSR; use ssr: false to disable server-side rendering.