Gatsby生产构建报useMantineColorScheme上下文调用错误
Gatsby生产构建报useMantineColorScheme上下文不存在错误解决方案
开发模式正常、生产构建触发该报错,本质是SSR构建阶段调用hook时找不到对应的Provider上下文,按以下优先级排查修复:
- 优先对齐依赖版本
你当前的依赖存在版本不匹配问题:@mantine/core、@mantine/hooks为4.2.9版本,但gatsby-plugin-mantine停留在4.0.0版本,跨小版本的上下文引用不一致是这类报错最常见的原因。
执行以下命令对齐版本并清除缓存:
80%的同类问题执行完这一步就能直接解决yarn upgrade gatsby-plugin-mantine@^4.2.9 yarn clean yarn build - 检查gatsby-config.js插件顺序
确认gatsby-plugin-mantine放在plugins数组的靠前位置,必须排在gatsby-plugin-sass、自定义页面生成类插件之前,插件加载顺序靠后会导致Provider注入时机晚于组件渲染时机,触发报错。注意:4.x版本的gatsby-plugin-mantine会自动注入ColorSchemeProvider和MantineProvider,不需要你手动在根组件重复包裹,重复包裹反而会造成上下文作用域隔离,触发同类报错。
- 校验hook调用位置
排查所有调用useMantineColorScheme的代码,确保没有出现在以下位置:- gatsby-ssr.js、gatsby-browser.js的顶层作用域
- wrapPageElement、wrapRootElement导出函数的外层逻辑
- 非React组件/自定义Hook的普通工具函数内
所有hook调用必须放在React函数组件、自定义Hook的内部顶层作用域。
- 处理SSR阶段的客户端专属逻辑
如果你的组件在SSR渲染阶段就会执行顶层逻辑,需要加客户端挂载判断,避免构建阶段调用依赖浏览器上下文的hook:import { useEffect, useState } from 'react' import { useMantineColorScheme } from '@mantine/core' export default function ThemeComponent() { const [mounted, setMounted] = useState(false) // 仅客户端挂载完成后再调用hook获取配色 const { colorScheme, toggleColorScheme } = mounted ? useMantineColorScheme() : { colorScheme: 'light', toggleColorScheme: () => {} } useEffect(() => { setMounted(true) }, []) // 未挂载时返回占位,不执行主题相关逻辑 if (!mounted) return null return <button onClick={() => toggleColorScheme()}>切换主题</button> } - 兜底手动注入Provider
如果以上步骤都无法解决,说明插件自动注入逻辑失效,可以手动在gatsby-browser.js和gatsby-ssr.js两个文件中同时添加根组件包裹逻辑:
添加完成后,把gatsby-config.js中plugins数组里的// gatsby-browser.js、gatsby-ssr.js 需添加完全相同的代码 const React = require('react') const { ColorSchemeProvider, MantineProvider } = require('@mantine/core') exports.wrapRootElement = ({ element }) => { return React.createElement( ColorSchemeProvider, { defaultColorScheme: 'light' }, React.createElement(MantineProvider, { withGlobalStyles: true }, element) ) }gatsby-plugin-mantine删除,避免重复包裹冲突,再重新执行构建即可。
内容的提问来源于stack exchange,提问作者sofifa
相关产品推荐
相关产品推荐

