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

React集成OpenAI API报错:Module parse failed,未启用top-level-await

解决React中使用OpenAI API时的"top-level-await experiment is not enabled"错误

错误原因

你代码里的await openai.createCompletion(...)直接写在了顶层作用域(函数外部),React项目默认的打包配置没有启用顶层await的实验特性,导致打包失败。另外从功能逻辑来说,你需要的是用户点击提交按钮后再触发API调用,而非组件加载时自动调用,所以这个顶层调用本身也不符合需求。

修复步骤

  1. 将OpenAI初始化和API调用移到表单提交事件处理函数内,并把onFormSubmit改为异步函数,合法使用await。
  2. 添加加载状态处理,避免用户重复提交,同时给用户反馈。
  3. 处理API调用的成功和失败情况,更新组件状态展示结果或错误信息。

修正后的完整代码

import React, { Component } from 'react'
import { Container, Form, Button, Card } from 'react-bootstrap'
import { Configuration, OpenAIApi } from "openai";

class ProductDescription extends Component {
    constructor() {
        super()
        this.state = {
            heading: 'The response from the AI will be shown here',
            response: '...... await the response',
            isLoading: false
        }
    }

    onFormSubmit = async e => {
        e.preventDefault()
        const formData = new FormData(e.target),
              formDataObj = Object.fromEntries(formData.entries())
        
        if (!formDataObj.productName.trim()) return

        // 设置加载状态
        this.setState({
            heading: `AI product description suggestions for: ${formDataObj.productName}`,
            response: 'Loading...',
            isLoading: true
        })

        try {
            // 初始化OpenAI客户端
            const configuration = new Configuration({
                apiKey: 'your-api-key', // 注意:生产环境不要硬编码,建议通过后端代理
            });
            const openai = new OpenAIApi(configuration);

            // 调用OpenAI API
            const response = await openai.createCompletion({
                model: "text-davinci-003",
                prompt: `generate product description explanation for the following product: ${formDataObj.productName}`,
                temperature: 1,
                max_tokens: 200,
                top_p: 1,
                frequency_penalty: 0,
                presence_penalty: 0,
            });

            // 更新状态展示结果
            this.setState({
                response: response.data.choices[0].text.trim(),
                isLoading: false
            })
        } catch (error) {
            // 处理错误
            this.setState({
                response: `Error: ${error.message || 'Failed to fetch AI response'}`,
                isLoading: false
            })
            console.error('OpenAI API error:', error)
        }
    }

    render() {
        const { isLoading } = this.state
        return (
            <div>
                <Container>
                    <br />
                    <br />
                    <h1>generate product descriptions</h1>
                    <br />
                    <h4>generate product descriptions for any types of products, simply enter the name and productdescriptions to the card</h4>
                    <br />
                    <br />
                    <Form onSubmit={this.onFormSubmit}>
                        <Form.Group className='mb-3' controlId='formBasicEmail'>
                            <Form.Label>What products would you like to get a description for?</Form.Label>
                            <Form.Control type='text' name='productName' placeholder='Enter product name' />
                            <Form.Text className='text-muted'>Enter as much information as possible for more accurate descriptions</Form.Text>
                        </Form.Group>
                        <Button variant="primary" size="lg" type="submit" disabled={isLoading}>
                            {isLoading ? 'Generating...' : 'Get AI suggestions'}
                        </Button>
                    </Form>
                    <br />
                    <br />

                    <Card>
                        <Card.Body>
                            <Card.Title><h1>{this.state.heading}</h1></Card.Title>
                            <hr />
                            <br />
                            <Card.Text>
                                <h4>
                                    {this.state.response}
                                </h4>
                            </Card.Text>
                        </Card.Body>
                    </Card>
                </Container>
                <br />
                <br />
                <br />
                <br />
            </div>
        )
    }
}

export default ProductDescription

额外提醒

  • 不要在客户端代码中硬编码OpenAI API Key,这会导致密钥泄露,被他人盗用。生产环境建议搭建一个后端服务,通过后端代理调用OpenAI API,前端只和自己的后端接口通信。
  • 如果你确实需要使用顶层await(比如组件初始化时调用API),可以修改Webpack配置,在webpack.config.js中添加experiments: { topLevelAwait: true },但这不符合你当前的功能需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:30:56