MUI样式开发报TypeError: Cannot read properties of undefined (reading 'up')求助
问题原因
报错TypeError: Cannot read properties of undefined (reading 'up')的核心是theme.breakpoints为未定义状态,本质是你调用的makeStyles方法没有正确拿到MUI的主题对象。
解决方案
第一步:检查根组件的ThemeProvider配置
确保你的应用最外层已经用ThemeProvider包裹,并且传入了正确的主题实例:
// 入口文件(通常是App.js或index.js) import { ThemeProvider, createTheme } from '@mui/material/styles'; import CssBaseline from '@mui/material/CssBaseline'; // 即使使用默认主题也需要显式创建实例 const theme = createTheme(); function RootApp() { return ( <ThemeProvider theme={theme}> <CssBaseline /> {/* 你的所有业务组件都要放在ThemeProvider内部 */} </ThemeProvider> ); } export default RootApp;
第二步:给makeStyles开启withTheme配置
MUI v5中@mui/styles的makeStyles默认不会自动注入主题对象,需要显式开启参数:
修改你styles.js的导出部分,原有样式代码完全不需要改动,只需要在makeStyles的第二个参数加withTheme: true:
// styles.js 修改后代码 import { makeStyles } from '@mui/styles'; import { alpha } from '@mui/material/styles'; const drawerWidth = 0; export default makeStyles((theme) => ({ // 你原来的所有样式属性完全保留不动 appBar: { boxShadow: 'none', borderBottom: '1px solid rgba(0, 0, 0, 0.12)', [theme.breakpoints.up('sm')]: { width: `calc(100% - ${drawerWidth}px)`, marginLeft: drawerWidth, }, }, // ... 剩下的原有样式全部不变 }), { withTheme: true }); // 只需要加这行配置
可选兜底方案
如果还是存在偶发的theme为空问题,可以直接给回调的theme参数指定默认主题兜底:
import { makeStyles } from '@mui/styles'; import { alpha, createTheme } from '@mui/material/styles'; const defaultTheme = createTheme(); const drawerWidth = 0; export default makeStyles((theme = defaultTheme) => ({ // 原有样式不变 }));
版本兼容检查
确保所有MUI相关依赖包版本统一,不要同时安装v4版本的@material-ui包和v5版本的@mui包,避免依赖冲突。
修改完成后重启本地开发服务,清除缓存后再验证即可解决报错。
内容的提问来源于stack exchange,提问作者Sandy
相关产品推荐
相关产品推荐

