全新安装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错误问题。
问题原因及修复方案
缺失核心依赖
DataGrid属于MUI X组件库,不在基础@mui/material包内,你当前的package.json里没有安装@mui/x-data-grid,这是导致错误的直接原因之一。版本兼容性问题
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适配问题:
同时更新package.json中npm install react@^18.2.0 react-dom@^18.2.0peerDependencies里的React版本为^18.2.0。 - 重启开发服务器:
npm run dev
完成以上操作后,Hook错误应该会消失,DataGrid可以正常渲染。
内容的提问来源于stack exchange,提问作者Travis Heeter
相关产品推荐
相关产品推荐

