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

安装Chakra UI后报React未定义、无法读取useMemo属性错误如何解决

问题描述

执行官方推荐命令安装Chakra UI后,启动应用触发报错,安装命令如下:

npm i @chakra-ui/react @emotion/react@^11 @emotion/styled@^11 framer-motion@^6

运行时抛出的第一个错误:

Uncaught TypeError: Cannot read properties of null (reading 'useMemo')
    at Object.useMemo (react.development.js:1648:1)
    at ThemeProvider (chakra-ui-system.esm.js:35:1)
    at renderWithHooks (react-dom.development.js:16175:1)
    at mountIndeterminateComponent (react-dom.development.js:20913:1)
    at beginWork (react-dom.development.js:22416:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4161:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4210:1)
    at invokeGuardedCallback (react-dom.development.js:4274:1)
    at beginWork$1 (react-dom.development.js:27405:1)
    at performUnitOfWork (react-dom.development.js:26513:1)

随后抛出组件层级错误提示:

The above error occurred in the <ThemeProvider> component:

    at ThemeProvider (http://localhost:3000/static/js/bundle.js:20476:27)
    at ChakraProvider (http://localhost:3000/static/js/bundle.js:14271:24)
    at ChakraProvider (http://localhost:3000/static/js/bundle.js:15656:23)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

排查chakra-ui-system.esm.js源码时发现,触发错误的代码行调用了React.useMemo,但当前作用域下导入的React值为null,对应代码:

var computedTheme = React.useMemo(function () {
    return toCSSVar(theme);
  }, [theme]);

应用本身仅保留最精简的渲染逻辑,排除业务代码问题,入口代码如下:

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <ChakraProvider><div></div></ChakraProvider>
  </React.StrictMode>
);

问题根因

这是典型的依赖版本不兼容或React多实例问题,核心触发原因有两个:

  • 版本不匹配:当前最新版@chakra-ui/react(v2.x及以上)仅支持React 18+,如果项目本地使用的是React 17及以下版本,Chakra UI的ESM模块导入React时会出现空值,调用Hook时直接抛出空指针错误。
  • 依赖树异常:安装过程中依赖解析出错,导致node_modules中存在多份React副本,Chakra UI引用的React实例和项目实际运行的React实例不一致,违反React Hook调用规则触发报错。
修复方案

按优先级依次尝试以下操作:

  • 对齐依赖版本
    • 如果项目继续使用React 17,卸载当前高版本Chakra UI,安装适配React 17的v1.x版本:
      npm uninstall @chakra-ui/react framer-motion
      npm i @chakra-ui/react@1.8.8 framer-motion@^5
      
    • 如果要使用最新版Chakra UI,将项目内的react、react-dom升级到18及以上版本即可。
  • 清理重装依赖
    版本对齐后仍报错的话,删除损坏的依赖目录和锁文件后重新安装:
    rm -rf node_modules package-lock.json
    npm install
    
  • 强制单React实例(自定义打包配置场景使用)
    如果项目修改过webpack/Vite等打包工具配置,在配置中添加别名强制所有模块引用同一份React实例,webpack配置示例:
    module.exports = {
      resolve: {
        alias: {
          react: require.resolve('react'),
          'react-dom': require.resolve('react-dom')
        }
      }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 18:06:27