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

Next.js 13搭配Radix UI报错:TypeError: react.createContext is not a function

解决Next.js 13中Radix UI Select组件的TypeError: $9g4ps$react.createContext is not a function报错

最可能的原因:未标记组件为Client Component

Next.js 13的App Router默认将组件视为Server Components,而Radix UI的Select组件依赖React Context(createContext是客户端专属API),无法在Server Components中运行。你的代码里没有添加客户端组件标记,这是核心问题。

修复方法:

在组件文件顶部添加'use client'指令,强制组件在客户端运行:

'use client';
import * as Select from '@radix-ui/react-select';

export default () => (
    <Select.Root>
      <Select.Trigger>
        <Select.Value placeholder="选择选项" />
        <Select.Icon />
      </Select.Trigger>

      <Select.Portal>
        <Select.Content>
          <Select.ScrollUpButton />
          <Select.Viewport>
            <Select.Item value="option1">
              <Select.ItemText>选项1</Select.ItemText>
              <Select.ItemIndicator />
            </Select.Item>
            <Select.Item value="option2">
              <Select.ItemText>选项2</Select.ItemText>
              <Select.ItemIndicator />
            </Select.Item>
          </Select.Viewport>
          <Select.ScrollDownButton />
        </Select.Content>
      </Select.Portal>
    </Select.Root>
)

注:给Select.Value加上placeholder属性,避免渲染空值导致的额外警告。

其他排查方向

如果添加'use client'后仍报错,检查以下几点:

  • 依赖版本兼容性:确保项目中react和react-dom版本为18.x(Next.js 13默认依赖),同时@radix-ui/react-select为最新稳定版。可执行以下命令重新安装依赖:
    rm -rf node_modules package-lock.json
    npm install
    
  • 重复React实例:项目中可能存在多个React版本,导致Context API无法正常工作。执行npm ls react查看依赖树,若有多个React实例,手动调整依赖版本统一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 17:05:51