查看: 85|回覆: 0

[cause]: TypeError: e_.createContext is not a function (Next.js 15)

[複製鏈接]

4

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2012-2-24
發表於 2025-1-5 08:44:00 | 顯示全部樓層 |閲讀模式

开发 Next.js 项目遇到报错: [cause]: TypeError: e_.createContext is not a function 

出现这个报错的原因是在 Next.js 项目中,在 Server Component 中使用了MUI组件,但是MUI组件没有做 SSR 适配就会导致这个报错。

解决办法

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

'use client';  // 加上这行

import React from 'react';
import UploadIcon from '@mui/icons-material/Upload';
import Button from '@mui/material/Button';
import Snackbar from '@mui/material/Snackbar';
import Alert from '@mui/material/Alert';
import { styled } from '@mui/material/styles';
import axios from 'axios';

const Input = styled('input')({
  display: 'none',
});

const App: React.FC = () => {
  const [open, setOpen] = React.useState(false);
  const [message, setMessage] = React.useState('');
  const [severity, setSeverity] = React.useState<'success' | 'error'>('success');

  const handleChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      try {
        const formData = new FormData();
        formData.append('file', file);

        const response = await axios.post('https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload', formData, {
          headers: {
            authorization: 'authorization-text',
            'Content-Type': 'multipart/form-data',
          },
        });

        if (response.status === 200) {
          setMessage(`${file.name} file uploaded successfully`);
          setSeverity('success');
        }
      } catch (error) {
        setMessage(`${file.name} file upload failed.`);
        setSeverity('error');
      } finally {
        setOpen(true);
      }
    }
  };

  const handleClose = () => {
    setOpen(false);
  };

  return (
    <>
      <label htmlFor="upload-file">
        <Input accept="image/*" id="upload-file" type="file" onChange={handleChange} />
        <Button variant="contained" component="span" startIcon={<UploadIcon />}>
          Click to Upload
        </Button>
      </label>
      <Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
        <Alert onClose={handleClose} severity={severity} sx={{ width: '100%' }}>
          {message}
        </Alert>
      </Snackbar>
    </>
  );
};

export default App;

 

回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.