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

MUI DataGrid组件报错:已设置行唯一id仍提示需唯一id

解决MUI DataGrid行ID唯一性报错的排查方案

1. 先确认行数据的标识字段真的有效

盯着控制台打印的props.rows仔细核对:

  • 检查每一行的id或你用来替代的studentId是否真实存在,有没有出现undefined、null的情况?比如接口返回的字段名可能是student_id或StudentId(大小写不一致),导致你取错了字段。
  • 检查有没有重复值:两条数据的studentId一模一样也会触发报错。可以加一段临时代码排查:
// 在GradeTable组件里添加这段,找出有问题的行
import { useEffect } from 'react';

export const GradeTable = (props: GradeTableProps) => {
  useEffect(() => {
    if (!props.rows) return;
    // 找出无标识或重复的行
    const badRows = props.rows.filter(row => {
      const id = row.studentId; // 替换成你用的标识字段
      if (!id) return true;
      // 检查重复
      return props.rows.filter(r => r.studentId === id).length > 1;
    });
    console.log('不符合要求的行:', badRows);
  }, [props.rows]);

  // 原组件代码...
};

2. 检查getRowId的使用是否正确

别忽略拼写和字段取值细节:

  • 确保getRowId是全小写的,别写成getRowID(大写D),组件识别不了。
  • 箭头函数里返回的必须是原始类型值(字符串/数字),如果studentId是嵌套对象,得取到具体值,比如row.studentId.id。
    正确写法示例:
<DataGrid
  rows={props.rows}
  columns={columns}
  pageSize={5}
  rowsPerPageOptions={[5]}
  getRowId={(row) => row.studentId} // 确保studentId是字符串/数字类型
/>

3. 手动给行添加标准id字段试试

如果getRowId不管用,直接给每一行补上id字段:

export const GradeTable = (props: GradeTableProps) => {
  // 手动处理行数据,把studentId转成id字段
  const processedRows = props.rows?.map(row => ({
    ...row,
    id: row.studentId // 确保这里的studentId有效
  })) || [];

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        rows={processedRows}
        columns={columns}
        pageSize={5}
        rowsPerPageOptions={[5]}
      />
    </div>
  );
};

4. 排查DataGrid版本问题

如果是旧版本的MUI DataGrid,可能存在getRowId的兼容性问题,试试升级到最新稳定版,或者查看对应版本的官方文档确认用法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:10:22