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

Next.js 13 + TypeScript集成Formik报错:React.createContext is not a function

解决Next.js 13(TypeScript)中Formik报错“TypeError: React.createContext is not a function”

问题原因

Next.js 13的App Router默认将所有组件视为服务器组件,而Formik内部依赖React的客户端专属API(React.createContext),服务器组件环境中无法调用这类API,因此触发报错。错误溯源指向(sc_server)也验证了这一点——代码正运行在服务器端上下文。

解决方案

1. 声明组件为客户端组件

在使用Formik的组件文件顶部添加'use client'指令,强制该组件在客户端环境运行,这样就能正常访问React的客户端API了。

修改后的组件代码:

'use client'; // 关键:添加这一行声明客户端组件
import * as React from 'react';
import {
  Formik,
  FormikHelpers,
  FormikProps,
  Form,
  Field,
  FieldProps,
} from 'formik';

interface MyFormValues {
  firstName: string;
}

export const MyApp: React.FC<{}> = () => {
  const initialValues: MyFormValues = { firstName: '' };
  return (
    <div>
      <h1>My Example</h1>
      <Formik
        initialValues={initialValues}
        onSubmit={(values, actions) => {
          console.log({ values, actions });
          alert(JSON.stringify(values, null, 2));
          actions.setSubmitting(false);
        }}
      >
        <Form>
          <label htmlFor="firstName">First Name</label>
          <Field id="firstName" name="firstName" placeholder="First Name" />
          <button type="submit">Submit</button>
        </Form>
      </Formik>
    </div>
  );
};

2. 确保Formik版本兼容

检查package.json中的Formik版本,建议使用最新稳定版(v2.x及以上),确保其兼容React 18和Next.js 13。如果版本过旧,执行以下命令更新:

npm update formik
# 或 yarn upgrade formik

验证

修改后重新启动Next.js开发服务器,表单应该能正常渲染并提交,控制台不再出现React.createContext is not a function的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 23:55:36