VS Code中Material UI Popover组件TypeScript报错排查请求
React + TypeScript + Material UI 运行正常但VS Code报TypeScript错误
依赖版本
{ "react": "^18.3.1", "@mui/lab": "^5.0.0-alpha.170", "@mui/material": "^5.15.18", "typescript": "^5.2.2" }
问题说明
代码可正常运行,但VS Code中持续出现TypeScript错误,无法定位问题根源。
组件代码
import React, { useState } from "react"; import Box from "@mui/material/Box"; import Button from "@mui/material/Button"; import Popover from "@mui/material/Popover"; import Typography from "@mui/material/Typography"; import { alpha } from "@mui/material/styles"; const SimplePopover = React.memo(() => { const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(document.body); const handleClose = () => { setAnchorEl(null); }; const open = Boolean(anchorEl); const id = open ? "simple-popover" : undefined; let details = "你的浏览器正在阻止应用的弹窗,请启用弹窗后重试。\n"; details += "你可以点击网址栏右侧的图标,"; details += '选择"始终允许..."选项,点击完成后刷新页面即可。'; return ( <Box> <Popover id={id} open={open} anchorEl={anchorEl} onClose={handleClose} anchorOrigin={{ vertical: "center", horizontal: "center" }} transformOrigin={{ vertical: "center", horizontal: "center" }} > <Typography component="div" sx={{ p: 2 }}> <h2 style={{ color: "#0747a6" }}> 请关闭弹窗拦截 </h2> <div style={{ whiteSpace: "pre-line" }}> {details} </div> <img src="images/popups-blocked.png" alt={details} style={{ paddingTop: "10px", paddingBottom: "10px" }} /> <Box sx={{ display: "flex", justifyContent: "flex-end", paddingTop: "10px", paddingBottom: "10px", borderTop: 1, borderColor: alpha("#0747a6", 0.1) }}> <Button variant="contained" onClick={handleClose} sx={{ mr: 1, color: "#fff", backgroundColor: "#0747a6" }}> 好的,我知道了 </Button> </Box> </Typography> </Popover> </Box> ); }); export default SimplePopover;
VS Code错误信息
根据截图显示,错误为:'document' is not defined,指向useState初始化时的document.body。
解决方案
- 修复初始化逻辑:React组件初始化阶段直接访问
document会触发TypeScript环境检测警告(尤其在SSR场景下document不存在),可改为组件挂载后设置初始值:
import { useEffect } from 'react'; const SimplePopover = React.memo(() => { const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null); useEffect(() => { setAnchorEl(document.body); }, []); // 其余代码不变 });
- 确保TypeScript配置包含DOM环境:检查
tsconfig.json的compilerOptions.lib字段,确认包含dom:
{ "compilerOptions": { "lib": ["dom", "dom.iterable", "esnext"] } }
- 临时绕过检测(不推荐):若无需考虑SSR场景,可通过类型断言临时消除警告:
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>((document as globalThis.Document).body);
内容的提问来源于stack exchange,提问作者Praveen
相关产品推荐
相关产品推荐

