[cause]: TypeError: e_.createContext is not a function (Next.js 15)
开发 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;
![]() | 本作品采用 知识共享署名-非商业性使用 2.5 中国大陆许可协议进行许可。 |