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

Next.js集成stream-chat-react报错:ReferenceError: getComputedStyle is not defined

问题解决:Next.js中使用stream-chat-react出现ReferenceError: getComputedStyle is not defined

错误原因

getComputedStyle是浏览器专属API,Next.js默认的服务端渲染(SSR)阶段不存在这个方法。stream-chat-react的Chat组件在服务端渲染时调用了该API,导致报错。

解决方案

通过Next.js的dynamic导入功能,将Chat组件设置为仅在客户端渲染,禁用SSR:

修改index.js代码如下:

import React from "react";
//! packages
import Pusher from "pusher-js";
import { StreamChat } from "stream-chat";
import Cookies from "universal-cookie";
//! components
import ChannelListContainer from "../components/ChannelListContainer";
import ChannelContainer from "../components/ChannelContainer";
import dynamic from 'next/dynamic';

// 动态导入Chat组件,禁用服务端渲染
const Chat = dynamic(() => import('stream-chat-react').then(mod => mod.Chat), {
  ssr: false,
  loading: () => <div>加载聊天组件中...</div> // 可选:添加加载状态提示
});

const apiKey = process.env.CHAT_API_KEY;
const client = StreamChat.getInstance(apiKey);

export default function Home() {
  return (
    <div className="app__container">
      <h2>Developer Chat App</h2>
      <Chat client={client} theme="team light">
        <ChannelListContainer />
        <ChannelContainer />
      </Chat>
    </div>
  );
}

额外说明

  • 如果后续使用stream-chat-react的其他组件(如ChannelList、MessageList等)出现类似浏览器API未定义的错误,同样可以用dynamic导入并禁用SSR的方式处理。
  • 确保StreamChat客户端的初始化逻辑中,涉及用户认证、连接等操作仅在客户端执行(可通过useEffect或条件判断typeof window !== 'undefined'实现)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:15:39