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

在Gatsby/React项目中使用MaterialUI创建主题时出现color属性读取错误

Gatsby/React项目配置Material UI自定义主题时出现TypeError错误

错误信息

Uncaught TypeError: Cannot read properties of undefined (reading 'color')
    at component---src-pages-index-tsx.js:3230:104
    at transformedStyleArg (component---src-pages-index-tsxhead.js:8985:40)
    at handleInterpolation (commons.js:1179:24)
    at serializeStyles (commons.js:1304:15)
    at component---src-pages-index-tsxhead.js:700:91
    at commons.js:798:12
    at renderWithHooks (framework.js:17108:18)
    at updateForwardRef (framework.js:20024:20)
    at beginWork (framework.js:22434:16)
    at beginWork$1 (framework.js:28224:14)

我的gatsby-browser.tsx代码

import React from "react";
import { ThemeProvider, createTheme } from "@mui/material/styles";

const theme = createTheme(
  {
    typography: {
      fontFamily: "sans-serif",
    }
  }
);

export const wrapRootElement = ({ element }) => {
  return <ThemeProvider theme={theme}>{element}</ThemeProvider>;
};

相关依赖版本(来自package.json)

"@mui/icons-material": "5.14.6",
    "@mui/material": "5.14.6",
    "@mui/material-next": "6.0.0-alpha.98",
    "gatsby": "5.12.1",
    "react": "18.2.0",

问题原因

同时安装了Material UI的稳定版(v5.14.6)和测试版(v6 alpha),两个版本的主题系统结构不兼容,导致组件访问主题属性时找不到对应值,触发错误。

解决步骤

  • 卸载冲突的测试版包
    执行命令移除@mui/material-next:

    # npm
    npm uninstall @mui/material-next
    
    # yarn
    yarn remove @mui/material-next
    
  • 确保依赖版本一致
    检查package.json,保证所有@mui/*相关包的版本统一(当前保持5.14.6即可)。

  • 清理缓存并重装依赖

    # npm
    rm -rf node_modules package-lock.json
    npm install
    
    # yarn
    rm -rf node_modules yarn.lock
    yarn install
    
  • 重启开发服务
    关闭当前Gatsby开发服务器,重新执行gatsby develop即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 13:01:06