NextJS中SpeechSynthesisUtterance is not defined错误解决咨询
修复SpeechSynthesisUtterance is not defined错误
问题根源
你的代码存在两个核心问题:
- 组件初始化阶段就直接创建
SpeechSynthesisUtterance实例并调用speak方法,而非在按钮点击时执行,导致组件一渲染就触发朗读,且服务端渲染环境(如Next.js)不存在浏览器的SpeechSynthesis API,重启服务器后触发服务端渲染时就会报错。 - 未明确限定代码仅在浏览器环境下执行,服务端环境没有
window对象及相关API,直接调用会导致未定义错误。
修复代码
export default function Main() { const handleSpeak = () => { // 仅在浏览器环境下执行语音朗读逻辑 if (typeof window !== 'undefined' && window.speechSynthesis) { const text = new window.SpeechSynthesisUtterance("Hello world!"); window.speechSynthesis.speak(text); } }; return <button onClick={handleSpeak}>Click me</button>; }
修复说明
- 将语音朗读逻辑封装到点击事件回调
handleSpeak中,确保只有用户点击按钮时才执行,避免组件初始化时的不必要执行。 - 通过
typeof window !== 'undefined'判断当前环境是否为浏览器,同时校验window.speechSynthesis是否存在,避免服务端渲染时的API不存在错误。 - 明确使用
window.SpeechSynthesisUtterance和window.speechSynthesis,消除环境差异导致的变量查找问题。
内容的提问来源于stack exchange,提问作者Nick her if do it dab by Ed no
相关产品推荐
相关产品推荐

