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

如何在Remix.run中使用MUI?复杂代码执行遇TypeError问题

问题
  • 在Remix上简单安装MUI可正常运行,但编写复杂代码时MUI报错:Cannot read properties of undefined (reading 'type')
  • 使用包管理器:npm
  • 预期行为:实现支持多语言的简易MUI管理后台
  • 实际行为:出现包及依赖相关错误

错误堆栈跟踪

TypeError: Cannot read properties of undefined (reading 'type')
at decomposeColor (file:///C:/Users/R.Darabi/WebstormProjects/cst.core.remixpanel/build/index.js?t=1702373889291.464:2092:14)
at getLuminance (file:///C:/Users/R.Darabi/WebstormProjects/cst.core.remixpanel/build/index.js?t=1702373889291.464:2133:12)
at getContrastRatio (file:///C:/Users/R.Darabi/WebstormProjects/cst.core.remixpanel/build/index.js?t=1702373889291.464:2138:14)
at Object.getContrastText (file:///C:/Users/R.Darabi/WebstormProjects/cst.core.remixpanel/build/index.js?t=1702373889291.464:2459:24)
at file:///C:/Users/R.Darabi/WebstormProjects/cst.core.remixpanel/build/index.js?t=1702373889291.464:167142:27
at muiStyledFunctionResolver (file:///C:/Users/R.Darabi/WebstormProjects/cst.core.remixpanel/build/index.js?t=1702373889291.464:2023:28)
at transformedStyleArg (file:///C:/Users/R.Darabi/WebstormProjects/cst.core.remixpanel/build/index.js?t=1702373889291.464:1943:83)
at handleInterpolation (C:\Users\R.Darabi\WebstormProjects\cst.core.remixpanel\node_modules@emotion\serialize\dist\emotion-serialize.cjs.dev.js:149:24)
at Object.serializeStyles (C:\Users\R.Darabi\WebstormProjects\cst.core.remixpanel\node_modules@emotion\serialize\dist\emotion-serialize.cjs.dev.js:263:15)
at C:\Users\R.Darabi\WebstormProjects\cst.core.remixpanel\node_modules@emotion\styled\base\dist\emotion-styled-base.cjs.dev.js:167:34
错误名称:TypeError

解决方案

1. 检查MUI主题配置

这个错误大概率是主题中某个颜色值未正确定义导致的。getContrastText方法需要有效的颜色值计算对比度,若主题palette下的primary.main、secondary.main等配置为undefined或无效格式,就会触发报错。

  • 打开主题配置文件,确保所有颜色值为有效的CSS格式(如#hex、rgb()、rgba()或MUI内置颜色常量)。
  • 示例正确配置:
import { createTheme } from '@mui/material/styles';

const theme = createTheme({
  palette: {
    primary: {
      main: '#1976d2',
    },
    secondary: {
      main: '#dc004e',
    },
  },
});

2. 适配Remix服务端渲染

Remix是SSR框架,MUI在SSR环境下需正确初始化主题。若复杂组件涉及服务端样式计算,可能因主题未在服务端正确加载导致颜色值缺失。

  • 确保在Remix根路由中正确配置MUI的ThemeProvider及服务端样式处理逻辑,适配SSR流程。

3. 同步依赖版本

MUI与Emotion版本不兼容也可能引发此类问题:

  • 执行npm list @mui/material @emotion/react @emotion/styled查看版本,MUI v5需搭配Emotion v11及以上版本。
  • 版本不兼容时,执行npm update @mui/material @emotion/react @emotion/styled更新到兼容版本。

4. 排查动态颜色逻辑

检查复杂代码中动态生成颜色的逻辑,确保传递给MUI组件的颜色props无空值:

  • 为可能为空的颜色props设置默认值或非空校验。
  • 示例优化:
// 错误写法
<Button color={props.customColor}>按钮</Button>

// 正确写法
<Button color={props.customColor || 'primary'}>按钮</Button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:24:54