NextJS 13使用@mui/system时出现TypeError: 无法读取'primary'属性
NextJS 13 迁移后使用 @mui/system 报错:TypeError: Cannot read properties of undefined (reading 'primary')
之前在NextJS 12中使用@mui/styles的代码运行完全正常,迁移到NextJS 13并改用@mui/system后,出现TypeError: Cannot read properties of undefined (reading 'primary')错误,无法定位原因。因在NextJS 12中跟随教程时频繁遇到漏洞和错误,所以转用NextJS 13。
相关代码
import { createTheme } from '@mui/system'; import { AppBar, Box, Container, CssBaseline, Link, ThemeProvider, Toolbar, Typography, } from '@mui/material'; import Head from 'next/head'; import NextLink from 'next/link'; import classes from '../utils/classes'; export default function Layout({ title, description, children }) { const theme = createTheme({ components: { MuiLink: { defaultProps: { underline: 'hover', }, }, }, typography: { h1: { fontSize: '1.6rem', fontWeight: 400, margin: '1rem 0', }, h2: { fontSize: '1.4rem', fontWeight: 400, margin: '1rem 0', }, }, palette: { mode: 'light', primary: { main: '#f0c000', }, secondary: { main: '#208080', }, }, }); return ( <> <Head> <title>{title ? `${title} - My App` : 'My App'}</title> {description && <meta name="description" content={description}></meta>} </Head> <ThemeProvider theme={theme}> <CssBaseline /> <AppBar position="static" sx={classes.appbar}> <Toolbar sx={classes.toolbar}> <NextLink href="/" passHref> <Link> <Typography sx={classes.brand}>My App</Typography> </Link> </NextLink> </Toolbar> </AppBar> <Container component="main" sx={classes.main}> {children} </Container> <Box component="footer" sx={classes.footer}> <Typography>All rights reserved. My App.</Typography> </Box> </ThemeProvider> </> ); }
错误说明
报错核心是代码尝试读取undefined对象的primary属性,即theme.palette未被正确初始化。
解决步骤
1. 更换createTheme和ThemeProvider的导入来源
当前从@mui/system导入的createTheme生成的主题结构,无法被@mui/material的组件(如AppBar)正确识别。需要改为从@mui/material/styles导入:
// 替换原导入语句 import { createTheme, ThemeProvider } from '@mui/material/styles'; // 移除@mui/material中的ThemeProvider导入 import { AppBar, Box, Container, CssBaseline, Link, Toolbar, Typography, } from '@mui/material';
2. 检查classes文件的主题访问逻辑
错误大概率来自../utils/classes.js中对主题的引用。比如如果文件中有类似以下代码:
export default { appbar: { backgroundColor: (theme) => theme.palette.primary.main } };
当使用@mui/system的createTheme时,theme.palette会是undefined,更换导入来源后即可解决。
3. 确保依赖版本兼容
执行以下命令安装最新稳定版的MUI依赖,避免版本不兼容问题:
npm install @mui/material @emotion/react @emotion/styled @mui/material/styles
内容的提问来源于stack exchange,提问作者theonewhodoesntexist
相关产品推荐
相关产品推荐

