You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按示例配置NextJS 13 App Router+MUI 5仍遇报错求助

解决方案:Next.js 13 App Router + MUI 5 启动报错问题

错误分析

你遇到的两个核心问题:

  • useLayoutEffect 导入错误:源于emotion依赖包与React/Next.js版本不兼容
  • createContext 只能在客户端组件使用:MUI底层依赖emotion的Context API,而Next.js 13 App Router默认文件是服务器组件,无法直接运行客户端API

具体解决步骤

1. 确保React版本为18.x

MUI 5和Next.js 13要求React 18,低版本React会导致useLayoutEffect导出错误。检查package.json中的react版本:

{
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  }
}

如果版本不符,执行:

npm install react@latest react-dom@latest

2. 正确添加'use client'指令

不需要修改node_modules里的文件,只需在直接导入MUI组件的文件顶部添加指令:

  • 若你的app/page.tsx直接导入了MUI组件,在文件第一行添加:
'use client';

import { Button, Typography } from '@mui/material';

// 你的组件代码
export default function Home() {
  return (
    <div>
      <Typography variant="h1">Hello MUI</Typography>
      <Button variant="contained">Click Me</Button>
    </div>
  );
}
  • 更推荐的做法:将MUI组件封装到单独的客户端组件中,比如app/components/MuiContent.tsx:
'use client';

import { Button, Typography } from '@mui/material';

export default function MuiContent() {
  return (
    <div>
      <Typography variant="h1">Hello MUI</Typography>
      <Button variant="contained">Click Me</Button>
    </div>
  );
}

然后在app/page.tsx(服务器组件)中导入这个客户端组件:

import MuiContent from './components/MuiContent';

export default function Home() {
  return <MuiContent />;
}

3. 同步依赖版本并清理缓存

确保MUI和emotion相关包版本匹配,执行:

npm install @mui/material@latest @emotion/react@latest @emotion/styled@latest

然后删除node_modules、package-lock.json(或yarn.lock),重新安装依赖:

rm -rf node_modules package-lock.json
npm install

4. 检查Next.js配置

确保next.config.js中包含MUI官方要求的转译配置:

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  transpilePackages: ['@mui/material', '@mui/system', '@emotion/react', '@emotion/styled'],
};

module.exports = nextConfig;

内容的提问来源于stack exchange,提问作者Noam Hudson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 20:55:55