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

Vue3 SSR环境报错IntersectionObserver is not defined问题求助

问题原因

IntersectionObserver 属于浏览器专属的Web API,仅在浏览器运行环境中存在,Node.js 原生没有提供该 API 实现。
你的代码将 new IntersectionObserver() 写在了模块顶层作用域,SSR 阶段会在服务端(Node.js环境)提前执行该模块代码,直接触发变量未定义的报错;常规客户端构建的代码全程在浏览器环境运行,自然可以正常调用该API。

修复方案
  • 不要在顶层作用域初始化 IntersectionObserver 实例,将初始化和指令逻辑包裹在客户端环境判断的分支中,绝大多数SSR框架都会提供环境标识变量,比如 process.client、import.meta.env.SSR 可用于判断当前运行环境。
  • 滚动动画属于纯前端交互逻辑,服务端渲染阶段不需要处理,直接跳过相关逻辑即可,不会影响服务端输出的HTML结构正确性。
修改后代码示例
export default boot(async ({ app, isClient }) => {
  // 仅在客户端环境执行相关逻辑
  if (!isClient) return

  const animatedScrollObserver = new IntersectionObserver(
    (entries, animatedScrollObserver) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add('enter');
          animatedScrollObserver.unobserve(entry.target);
        }
      });
    }
  );

  app.directive('scrollanimation', {
    beforeMount(el) {
      el.classList.add('before-enter');
      animatedScrollObserver.observe(el);
    }
  })
})

内容的提问来源于stack exchange,提问作者hpa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:54:02