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

Redux Provider配置报错:useMemo空指针及react-refresh导入问题

Redux Provider配置报错排查方案

第一个错误:Uncaught TypeError: Cannot read properties of null (reading 'useMemo')

排查与解决步骤:

  • 确认DOM容器存在且加载时机正确:检查index.html中是否有<div id="root"></div>,并确保引入index.js的脚本标签放在<body>末尾,或用DOM加载事件包裹渲染逻辑:
    document.addEventListener('DOMContentLoaded', () => {
      const container = document.getElementById('root');
      const root = createRoot(container);
      root.render(
        <Provider store={store}>
          <TestComponent />
        </Provider>
      );
    });
    
  • 校验依赖版本兼容性:@reduxjs/toolkit与react/react-dom存在版本匹配要求(如RTK 2.x需React 18+),执行命令查看版本树:
    npm list react react-dom @reduxjs/toolkit react-redux
    
    若版本不兼容,升级对应依赖:
    npm install react@latest react-dom@latest @reduxjs/toolkit@latest react-redux@latest
    
  • 检查Slice文件正确性:确认transactionsSlice.js无语法错误,正确导出reducer,示例结构:
    import { createSlice } from '@reduxjs/toolkit';
    
    const initialState = { /* 初始状态定义 */ };
    
    const transactionsSlice = createSlice({
      name: 'transactions',
      initialState,
      reducers: { /* 业务reducer逻辑 */ }
    });
    
    export const { /* 导出action creators */ } = transactionsSlice.actions;
    export default transactionsSlice.reducer;
    

第二个错误:跨目录导入react-refresh/runtime.js

排查与解决步骤:

  • 移除手动导入的react-refresh:检查App.js及其他文件,删除直接导入../node_modules/react-refresh/runtime.js的语句——标准React项目无需手动引入该文件。
  • 彻底重置依赖环境:
    1. 删除node_modules、package-lock.json(或yarn.lock)
    2. 清除npm缓存:
      npm cache clean --force
      
    3. 重新安装依赖:
      npm install
      
  • 自定义webpack配置检查:若使用自定义webpack配置,确保react-refresh-loader的配置逻辑正确,避免生成跨src/目录的导入路径。

用户提供的代码片段:

index.js

import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './globals/Redux/store';

const container = document.getElementById('root');
const root = createRoot(container);

const TestComponent = () => <div>Hello World!</div>;

root.render(
  <Provider store={store}>
    <TestComponent />
  </Provider>
);

store.js

import { configureStore } from '@reduxjs/toolkit';
import transactionsReducer from './transactionsSlice';

export const store = configureStore({
  reducer: {
    transactions: transactionsReducer
  },
});

错误信息:

首次错误

Uncaught TypeError: Cannot read properties of null (reading 'useMemo')

重置依赖后错误

ERROR in ./src/App.js 1:40-126
Module not found: Error: You attempted to import /Users/joshbenson/Desktop/fw/frontend/node_modules/react-refresh/runtime.js which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.
You can either move it inside src/, or add a symlink to it from project's node_modules/.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 12:30:25