MUI v5.14.13报错:主题error属性值类型不符求助
MUI v5.14.13 报错排查:主题属性"error"为对象而非字符串/数字
问题描述
升级到MUI v5.14.13后,原本正常运行的项目突然出现如下报错:
MUI: The value found in theme for prop: "error" is an [Object] instead of string or number. Check if you forgot to add the correct dotted notation, eg, "background.paper" instead of "background".
报错源自style.js:34,即便组件未直接使用styled组件也会触发。例如以下全屏Dialog组件,点击Cancel按钮或其他启动按钮均会报错:
import * as React from "react"; import Dialog from "@mui/material/Dialog"; import AppBar from "@mui/material/AppBar"; import Toolbar from "@mui/material/Toolbar"; import IconButton from "@mui/material/IconButton"; import CloseIcon from "@mui/icons-material/Close"; import Slide from "@mui/material/Slide"; import { Box, Button, Stack } from "@mui/material"; const Transition = React.forwardRef(function Transition(props, ref) { return <Slide direction="up" ref={ref} {...props} />; }); const FullScreenDialog = ({ open, onClose }) => { return ( <div> <Dialog fullScreen open={open} onClose={onClose} TransitionComponent={Transition} > <AppBar sx={{ position: "relative" }}> <Toolbar> <IconButton edge="start" color="inherit" onClick={onClose} aria-label="close" > <CloseIcon /> </IconButton> </Toolbar> </AppBar> <Box margin={{ sm: 3, xs: 2 }}> <Stack spacing={1} direction="row" justifyContent="flex-end"> <Button variant="outlined" color="error" size="small" onClick={onClose} sx={{ borderRadius: 10, textTransform: "none", ":hover": { bgcolor: "error", color: "error", border: "error", }, }} > Cancel </Button> </Stack> </Box> </Dialog> </div> ); }; export default FullScreenDialog;
问题原因与解决方案
这个报错确实是MUI v5.14.13的更新导致的——该版本对主题属性的校验逻辑做了更严格的限制。
代码中的问题出在Button组件的sx属性里:
:hover: { bgcolor: "error", color: "error", border: "error", }
MUI主题中的"error"是一个包含main、light、dark等属性的颜色对象,而bgcolor、color这类CSS属性需要的是具体的颜色值(字符串或数字)。旧版本会自动兼容取error.main,但v5.14.13开始严格校验,因此抛出错误。
修正方法很简单,将这些属性改为具体的主题颜色路径,同时修正border的写法(应单独指定边框颜色而非直接覆盖整个border样式):
:hover: { bgcolor: "error.main", // 可根据需求替换为error.light或error.dark color: "#fff", // 建议用白色文字搭配error背景,也可使用theme.palette.common.white borderColor: "error.main", }
内容的提问来源于stack exchange,提问作者Udayendu
相关产品推荐
相关产品推荐

