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

Next TS项目使用react-social-media-embed遇TypeError错误求解决方案

问题原因

这个错误的核心原因是Next.js App Router默认将组件视为服务器组件,而react-social-media-embed依赖的react-youtube库中包含React类组件——服务器组件不支持渲染类组件,哪怕你只导入了InstagramEmbed,整个包在服务器端加载时会触发YouTubeEmbed相关类组件的初始化,从而抛出错误。

修复方案

方案1:直接将页面改为客户端组件

在page.tsx顶部添加'use client'指令,告诉Next.js这个组件要在客户端渲染:

'use client'; // 新增客户端组件声明
import { InstagramEmbed } from 'react-social-media-embed';
import styles from './page.module.css';

export default function Home() {
  return (
    <>
      <main className={`${styles.main} max-w-screen-xl font-serif font-thin`}>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <InstagramEmbed url="https://www.instagram.com/p/CUbHfhpswxt/" width={328} />
        </div>
      </main>
    </>
  )
}

方案2:封装独立的客户端Embed组件

如果不想把整个页面改成客户端组件,可以单独封装一个只负责渲染社交嵌入的客户端组件,避免影响页面其他服务器渲染的内容:

  1. 创建components/InstagramEmbedClient.tsx:
'use client';
import { InstagramEmbed } from 'react-social-media-embed';

type Props = {
  url: string;
  width?: number;
};

export default function InstagramEmbedClient({ url, width = 328 }: Props) {
  return <InstagramEmbed url={url} width={width} />;
}
  1. 在page.tsx中导入使用:
import InstagramEmbedClient from '@/components/InstagramEmbedClient';
import styles from './page.module.css';

export default function Home() {
  return (
    <>
      <main className={`${styles.main} max-w-screen-xl font-serif font-thin`}>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <InstagramEmbedClient url="https://www.instagram.com/p/CUbHfhpswxt/" width={328} />
        </div>
      </main>
    </>
  )
}
补充说明

两种方案的本质都是让包含类组件的react-social-media-embed在客户端环境中渲染,避开服务器组件的限制。方案2更灵活,适合页面大部分内容需要服务器渲染的场景。

内容的提问来源于stack exchange,提问作者one-hand-octopus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 03:47:05