React18+Next.js项目引入ReactFlow报错createContext不是函数求助
解决Next.js 14 + React 18中使用ReactFlow出现
createContext is not a function错误 问题详情
基于React 18、Next.js 14.0.3与TypeScript创建的项目,执行npm run dev可正常运行,但安装reactflow@^11.10.1并使用自定义Flow组件后,抛出错误:
Error: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function
Flow组件代码
import ReactFlow, { Controls, Background } from 'reactflow'; import 'reactflow/dist/style.css'; const edges = [{ id: '1-2', source: '1', target: '2' }]; const nodes = [ { id: '1', data: { label: 'Hello' }, position: { x: 0, y: 0 }, type: 'input', }, { id: '2', data: { label: 'World' }, position: { x: 100, y: 100 }, }, ]; function Flow() { return ( <div style={{ height: '100%' }}> <ReactFlow nodes={nodes} edges={edges}> <Background /> <Controls /> </ReactFlow> </div> ); } export default Flow;
page.tsx代码
import Flow from './components/canvas'; export default function Home() { return ( <main className='flex min-h-screen flex-col items-center justify-between p-24'> <h1>Testing head</h1> <Flow /> </main> ); }
package.json配置
{ "name": "demo-app", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "next": "14.0.3", "react": "^18", "react-dom": "^18", "reactflow": "^11.10.1" }, "devDependencies": { "@types/node": "^20", "@types/react": "^18", "@types/react-dom": "^18", "autoprefixer": "^10.0.1", "eslint": "^8", "eslint-config-next": "14.0.3", "postcss": "^8", "tailwindcss": "^3.3.0", "typescript": "^5" } }
解决方案
1. 将Flow组件标记为Client Component
Next.js 14的App Router默认将组件视为Server Component,而ReactFlow内部依赖createContext等React客户端专属API,必须显式声明组件为Client Component。在Flow组件顶部添加'use client';指令:
'use client'; // 新增该行 import ReactFlow, { Controls, Background } from 'reactflow'; import 'reactflow/dist/style.css'; // 其余代码保持不变
2. 确保React依赖版本一致
若依赖安装存在版本冲突,可清理缓存后重新安装:
rm -rf node_modules package-lock.json npm install
也可在package.json中指定React稳定版:
"dependencies": { "next": "14.0.3", "react": "^18.2.0", "react-dom": "^18.2.0", "reactflow": "^11.10.1" }
修改后执行npm install更新依赖。
3. 检查Next.js配置
确认next.config.js中无影响React导入的实验性配置,若存在可能干扰的设置,可暂时注释后测试。
原因说明
Next.js App Router中,Server Component无法调用React的客户端API(如createContext、useState、useEffect等),ReactFlow的核心功能依赖这些API,因此必须将使用ReactFlow的组件标记为Client Component才能正常运行。
内容的提问来源于stack exchange,提问作者imjayabal
相关产品推荐
相关产品推荐

