MUI DataGrid封装后点击筛选报useGridRootProps错误排查
问题原因
这个报错的核心是MUI DataGrid的内部React Context没有正确传递给调用useGridRootProps的内置组件(筛选面板、列菜单等),结合你的三层封装代码,问题由几个不规范的封装写法导致:
- 中间层透传props时直接覆盖了DataGrid要求的插槽和插槽属性配置。你在两层封装组件里,
components、componentsProps、initialState这类复合属性都是直接重新定义后传入,没有和上层传入的对应属性做合并,会完全覆盖掉DataGrid内置筛选、列菜单组件需要的默认上下文配置,导致这些组件渲染时拿不到Context。 - 受控属性没有配套对应回调。
ClientSideDataGrid中传入了受控分页属性page={page},但没有传入对应的onPageChange回调,会导致DataGrid内部状态和外部自定义状态冲突,触发渲染异常。 - (可选排查项)如果你的列生成函数
MigrationJobColumns、自定义分页组件DiscoverPagination内部直接调用了DataGrid的内部Hook(比如useGridApiContext、useGridRootProps),这些Hook会在DataGridPro组件挂载前就在外层组件执行,此时Context还未初始化,触发菜单交互时就会直接报错。 - (可选排查项)项目中如果存在多版本的
@mui/x-data-grid*依赖,会导致Context对象引用不一致,即使组件在子树里也拿不到正确的Context值。
修复方案
按以下步骤调整代码即可:
- 所有复合属性必须合并后再传入,禁止直接覆盖
调整ClientSideDataGrid.tsx的传参逻辑,合并上层传入的componentsProps,同时补全分页受控对应的回调:
调整<BaseDataGrid {...props} rowCount={props.rows.length} page={page} onPageChange={(newPage) => setPage(newPage)} componentsProps={{ ...props.componentsProps, pagination: { ...props.componentsProps?.pagination, dataLoadType: DataLoadType.CLIENT, RefreshRows: LoadRows, pageSize: props.pageSize ?? defaultPageSize, page: page, setPage: setPage } }} />BaseDataGrid.tsx中DataGridPro的配置,合并上层传入的components、componentsProps、initialState:
如果你用的是v6及以上版本的MUI X,把<DataGridPro {...props} localeText={determineLocaleFromBrowserSetting()} rowHeight={27} headerHeight={47} disableSelectionOnClick={true} disableVirtualization={props.disableVirtualization ?? false} pagination={props.enablePagination ?? true} pageSize={props.pageSize ?? defaultPageSize} rowsPerPageOptions={[props.pageSize ?? defaultPageSize]} components={{ ...props.components, Pagination: DiscoverPagination, NoRowsOverlay: props.CustomNoRowsOverlay ?? GridNoRowsOverlay }} componentsProps={{ ...props.componentsProps }} disableMultipleColumnsSorting initialState={{ ...props.initialState, sorting: { sortModel: props.initialSortModel } }} />components替换为slots、componentsProps替换为slotProps即可,旧的components系列API在兼容层存在透传问题,多层封装下不推荐使用。 - 排查Hook调用位置
所有用到DataGrid内部Hook的自定义组件,必须通过slots/components属性传入DataGridPro,不要在外层组件渲染流程中直接调用这些Hook;列定义中的renderCell/renderHeader回调是DataGrid渲染时在自身Context树内执行的,可以正常使用Hook,不要把Hook调用提到列生成函数的顶层。 - 检查依赖一致性
执行依赖检查命令,确认项目中只存在单一版本的@mui/x-data-grid-pro,不要同时安装@mui/x-data-grid和@mui/x-data-grid-pro,避免Context引用不匹配。
内容的提问来源于stack exchange,提问作者Michael Kostek
相关产品推荐
相关产品推荐

