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

Material UI V5升级后makeStyles内theme变量为undefined问题求助

解决方案

1. 解决StyledEngineProvider导入异常问题

你当前安装的@mui/material@5.1.0属于较早的v5正式版本,StyledEngineProvider从v5.2.0版本才正式加入@mui/material/styles导出路径,升级@mui/material到最新稳定版即可解决:

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

2. 解决makeStyles回调中theme为undefined问题

该问题由上下文不匹配导致:@mui/styles包导出的makeStyles默认使用独立的JSS上下文,默认不会读取@mui/material/styles导出的ThemeProvider传递的theme值,可任选以下一种方案解决:

  • 方案一:替换全局ThemeProvider的导入源
    将根文件index.js中ThemeProvider的导入路径从@mui/material/styles改为@mui/styles,传入的theme配置保持不变即可:
    // 修改前
    // import { ThemeProvider, StyledEngineProvider } from "@mui/material/styles";
    // 修改后
    import { StyledEngineProvider } from "@mui/material/styles";
    import { ThemeProvider } from "@mui/styles";
    
  • 方案二:手动给makeStyles传入默认theme
    不需要修改全局配置,直接在使用makeStyles的文件中导入你定义好的theme,作为第二个参数传入即可:
    import makeStyles from '@mui/styles/makeStyles';
    import theme from './theme/theme'; // 导入你定义的theme文件
    
    const useStyles = makeStyles((theme) => ({
      appBar: {
        backgroundColor: "white",
        height: "60px",
        padding: "0px 5em",
        [theme.breakpoints.between("xs", 'lg')]: {
          padding: "0px",
        },
      },
    }), { defaultTheme: theme }); // 传入默认theme
    

额外依赖说明

如果你的npm版本低于7,不会自动安装@mui/styles的对等依赖,可手动安装缺失依赖:

npm install jss @mui/private-theming

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:36:03