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

React-TS项目使用Material-UI触发Invalid hook call错误求助

解决React-TS项目中Material-UI引发的Invalid Hook Call错误

问题场景

在React-TS项目中使用Material-UI编写了表格函数组件,但运行时触发Invalid Hook Call错误,将Material-UI组件替换为原生HTML表格后问题消失。

组件代码如下:

import React, { useState } from 'react';
import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper } from '@material-ui/core';

interface RowData {
  id: number;
  name: string;
  age: number;
}

const TableExample: React.FC = () => {
  const [rows, setRows] = useState<RowData[]>([
    { id: 1, name: 'John', age: 25 },
    { id: 2, name: 'Jane', age: 30 },
    { id: 3, name: 'Bob', age: 40 },
  ]);

  const headers = ['ID', 'Name', 'Age'];

  return (
    <TableContainer component={Paper}>
      <Table>
        <TableHead>
          <TableRow>
            {headers.map((header) => (
              <TableCell key={header}>{header}</TableCell>
            ))}
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map((row) => (
            <TableRow key={row.id}>
              <TableCell>{row.id}</TableCell>
              <TableCell>{row.name}</TableCell>
              <TableCell>{row.age}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
};

export default TableExample;

错误信息

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at resolveDispatcher (bundle.js:10297:17)
    at Object.useContext (bundle.js:10303:24)
    at useTheme (bundle.js:3470:50)
    at useStyles (bundle.js:3314:70)
    at WithStyles (bundle.js:3551:21)
    at renderWithHooks (bundle.js:32016:22)
    at updateForwardRef (bundle.js:34587:24)
    at beginWork (bundle.js:36634:20)
    at HTMLUnknownElement.callCallback (bundle.js:21608:18)
    at Object.invokeGuardedCallbackDev (bundle.js:21652:20)

The above error occurred in the <WithStyles(ForwardRef(TableContainer))> component:

    at WithStyles (http://localhost:3000/static/js/bundle.js:3545:31)
    at TableExample (http://localhost:3000/static/js/bundle.js:114:74)
    at div
    at App

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.

排查情况

使用npm ls react检查React依赖,结果显示所有依赖均指向同一版本的React(deduped标识说明重复依赖已被去重):

├─┬ @emotion/react@11.10.6
│ ├─┬ @emotion/use-insertion-effect-with-fallbacks@1.0.0
│ │ └── react@18.2.0 deduped
│ └── react@18.2.0
├─┬ @emotion/style@0.8.0
│ ├─┬ @emotion/core@0.13.1
│ │ └── react@18.2.0 deduped
│ └── react@18.2.0 deduped
├─┬ @emotion/styled@11.10.6
│ └── react@18.2.0 deduped
├─┬ @mui/material@5.11.13
│ ├─┬ @mui/base@5.0.0-alpha.121
│ │ └── react@18.2.0 deduped
│ ├─┬ @mui/system@5.11.13
│ │ ├─┬ @mui/private-theming@5.11.13
│ │ │ └── react@18.2.0 deduped
│ │ ├─┬ @mui/styled-engine@5.11.11
│ │ │ └── react@18.2.0 deduped
│ │ └── react@18.2.0 deduped
│ ├─┬ @mui/utils@5.11.13
│ │ └── react@18.2.0 deduped
│ ├─┬ react-dom@18.2.0
│ │ └── react@18.2.0 deduped
│ ├─┬ react-transition-group@4.4.5
│ │ └── react@18.2.0 deduped
│ └── react@18.2.0 deduped
├─┬ @testing-library/react@13.4.0
│ └── react@18.2.0 deduped
└─┬ react-scripts@5.0.1
  └── react@18.2.0 deduped

项目package.json内容:

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.10.6",
    "@emotion/style": "^0.8.0",
    "@emotion/styled": "^11.10.6",
    "@fontsource/roboto": "^4.5.8",
    "@mui/material": "^5.11.13",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.5.2",
    "@types/node": "^16.18.18",
    "@types/react": "^18.0.28",
    "@types/react-dom": "^18.0.11",
    "react-scripts": "5.0.1",
    "typescript": "^4.9.5",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

解决方案

核心问题

你安装的是Material-UI v5版本(包名@mui/material),但代码中导入的是v4版本的包路径@material-ui/core,两者不匹配导致组件内部钩子调用环境异常,触发错误。

修复步骤

  1. 修正组件导入路径
    将组件中的导入语句从@material-ui/core改为@mui/material,修改后的代码如下:
import React, { useState } from 'react';
// 替换导入路径
import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper } from '@mui/material';

interface RowData {
  id: number;
  name: string;
  age: number;
}

const TableExample: React.FC = () => {
  const [rows, setRows] = useState<RowData[]>([
    { id: 1, name: 'John', age: 25 },
    { id: 2, name: 'Jane', age: 30 },
    { id: 3, name: 'Bob', age: 40 },
  ]);

  const headers = ['ID', 'Name', 'Age'];

  return (
    <TableContainer component={Paper}>
      <Table>
        <TableHead>
          <TableRow>
            {headers.map((header) => (
              <TableCell key={header}>{header}</TableCell>
            ))}
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map((row) => (
            <TableRow key={row.id}>
              <TableCell>{row.id}</TableCell>
              <TableCell>{row.name}</TableCell>
              <TableCell>{row.age}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
};

export default TableExample;
  1. 可选:清理并重新安装依赖
    为确保依赖环境一致,可执行以下操作:
  • 删除项目根目录下的node_modules文件夹和package-lock.json文件
  • 运行命令npm install重新安装所有依赖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 03:57:07