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

全新安装MUI Data Grid后出现Hook错误求助

解决MUI DataGrid的Hook错误问题

我使用了MUI官方文档中DataGrid示例的精简版本,但出现了如下Hook错误:
错误截图

以下是我的代码:

import Box from '@mui/material/Box';
import { DataGrid, type GridColDef } from '@mui/x-data-grid';

import './App.css'

const columns: GridColDef<(typeof rows)[number]>[] = [
  { field: 'id', headerName: 'ID', width: 90 },
  { field: 'lastName', headerName: 'Last name', width: 150},
  { field: 'firstName', headerName: 'First name', width: 150},
  { field: 'age', headerName: 'Age', type: 'number', width: 110}
];

const rows = [
  { id: 1, lastName: 'Snow', firstName: 'Jon', age: 14 },
  { id: 2, lastName: 'Lannister', firstName: 'Cersei', age: 31 },
];

export default function App() {
  return (
    <Box sx={{ height: 400, width: '100%' }}>
      <DataGrid
        rows={rows}
        columns={columns}
      />
    </Box>
  );
}

我的package.json配置如下:

{
  "name": "my-mui-app",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc -b && vite build",
    "lint": "eslint .",
    "preview": "vite preview"
  },
  "dependencies": {
    "@emotion/react": "^11.14.0",
    "@emotion/styled": "^11.14.1",
    "@fontsource/roboto": "^5.2.10",
    "@mui/material": "^9.0.0"
  },
  "peerDependencies":{
    "react": "^19.2.4",
    "react-dom": "^19.2.4"
  },
  "devDependencies": {
    "@eslint/js": "^9.39.4",
    "@types/node": "^24.12.2",
    "@types/react": "^19.2.14",
    "@types/react-dom": "^19.2.3",
    "@vitejs/plugin-react": "^6.0.1",
    "eslint": "^9.39.4",
    "eslint-plugin-react-hooks": "^7.0.1",
    "eslint-plugin-react-refresh": "^0.5.2",
    "globals": "^17.4.0",
    "typescript": "~6.0.2",
    "typescript-eslint": "^8.58.0",
    "vite": "^8.0.4"
  }
}

我需要让MUI DataGrid正常运行,恳请帮忙解决该Hook错误问题。


问题原因及修复方案

  1. 缺失核心依赖
    DataGrid属于MUI X组件库,不在基础@mui/material包内,你当前的package.json里没有安装@mui/x-data-grid,这是导致错误的直接原因之一。

  2. 版本兼容性问题
    React 19属于较新版本,MUI 9对其适配可能存在不完善的地方,Hook错误大概率和版本不匹配有关。

修复步骤

  • 安装@mui/x-data-grid依赖(选择对React兼容性更稳定的7.x版本):
    npm install @mui/x-data-grid@^7.0.0
    
  • (推荐)降级React到稳定的18.x版本,避免新API适配问题:
    npm install react@^18.2.0 react-dom@^18.2.0
    
    同时更新package.json中peerDependencies里的React版本为^18.2.0。
  • 重启开发服务器:
    npm run dev
    

完成以上操作后,Hook错误应该会消失,DataGrid可以正常渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.01 17:13:08