You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS中SpeechSynthesisUtterance is not defined错误解决咨询

修复SpeechSynthesisUtterance is not defined错误

问题根源

你的代码存在两个核心问题:

  1. 组件初始化阶段就直接创建SpeechSynthesisUtterance实例并调用speak方法,而非在按钮点击时执行,导致组件一渲染就触发朗读,且服务端渲染环境(如Next.js)不存在浏览器的SpeechSynthesis API,重启服务器后触发服务端渲染时就会报错。
  2. 未明确限定代码仅在浏览器环境下执行,服务端环境没有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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 01:50:25