解决 Next.js 报错:Server Error Error: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function
返回博客
前端开发#nextjs

解决 Next.js 报错:Server Error Error: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function

开发 Next.js 项目遇到报错:Server Error Error: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function

Jan 3, 20261 min read1

问题出现原因

报错:Server Error Error: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function

image.png

出现这个报错一般是在 Next.js 项目中,在 Server Component 中使用了第三方组件(比如 Antd Design 或者 Arco Design 组件库),但是第三方组件没有做 SSR 适配就会导致这个报错。

大多数第三方组件都会用到 DOM 相关的 API,但是在 Next.js 中,组件默认是 Server Component。只有在顶部显式声明了 use clientClient Component 才能使用 DOM 相关的 API

解决办法

解决办法就是在文件顶部添加 use client 声明,让组件变成 Client Component

示例

'use client';  // 加上这行

import React from 'react';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { Button, message, Upload } from 'antd';

const props: UploadProps = {
  name: 'file',
  action: 'https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload',
  headers: {
    authorization: 'authorization-text',
  },
  onChange(info) {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} file uploaded successfully`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  },
};

const App: React.FC = () => (
  <Upload {...props}>
    <Button icon={<UploadOutlined />}>Click to Upload</Button>
  </Upload>
);

export default App;

觉得这篇文章有帮助?

点个赞,我会知道这类内容值得继续写。

评论(0)

发表评论

还没有评论,欢迎留下第一条留言。

解决 Next.js 报错:Server Error Error: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function - 付小晨