You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

React中async函数报错‘await是保留字’,求正确用法指导

解决React中async/await的"await是保留字"错误

嘿,我一眼就看出问题出在哪了——你虽然把handleSubmit标记成了async函数,但你在普通的回调函数里用了await,这就触发了"await是保留字"的错误。毕竟await只能在async函数内部使用,而validateFieldsAndScroll的回调默认是普通函数,自然不能用await啦。

下面给你两种解决方案,第二种更推荐,代码结构会更清爽:

方案1:把回调改成async函数

直接给validateFieldsAndScroll的回调加上async关键字,这样里面就能正常用await了。不过要注意单独处理请求的错误:

handleSubmit = async (e) => {
  e.preventDefault();
  // 给回调函数加上async
  this.props.form.validateFieldsAndScroll(async (err, values) => {
    if (!err && !this.state.added) {
      try {
        this.setState({ submit: true });
        // 这里可以正常用await了,别忘了接收返回的response
        const response = await PopUpAdsService.create({
          name: values.name,
          photo: this.state.secureUrl,
          type: values.type,
          link: this.state.deepl,
          status: values.status,
        });
        
        console.log(response);
        if (response.data.status === 200) {
          Notification(
            'success',
            'Pop-up has been created successfully',
          );
          this.setState({ submit: false, added: true });
          setTimeout(() => {
            this.props.history.replace('/dashboard/pop-up');
          }, 2000);
        }
      } catch (error) {
        console.log(error);
        Notification(
          'error',
          `Oops! Error occured. ${error.response.data.message}`,
        );
        this.setState({ submit: false });
      }
    }
  });
};

方案2:使用Promise版本的表单验证(更推荐)

Ant Design的Form组件其实支持Promise风格的调用,不用传回调函数,这样能让你的async/await流程更连贯,错误处理也更统一:

handleSubmit = async (e) => {
  try {
    e.preventDefault();
    // 直接await表单验证,通过后拿到values,失败则进入catch
    const values = await this.props.form.validateFieldsAndScroll();
    
    if (!this.state.added) {
      this.setState({ submit: true });
      // 正常await请求并接收response
      const response = await PopUpAdsService.create({
        name: values.name,
        photo: this.state.secureUrl,
        type: values.type,
        link: this.state.deepl,
        status: values.status,
      });
      
      console.log(response);
      if (response.data.status === 200) {
        Notification(
          'success',
          'Pop-up has been created successfully',
        );
        this.setState({ submit: false, added: true });
        setTimeout(() => {
          this.props.history.replace('/dashboard/pop-up');
        }, 2000);
      }
    }
  } catch (error) {
    // 这里会同时捕获表单验证错误和请求错误
    console.log(error);
    let errorMessage = 'Oops! Error occured.';
    // 兼容不同错误场景的信息展示
    if (error.response?.data?.message) {
      errorMessage += ` ${error.response.data.message}`;
    } else if (error?.message) {
      errorMessage += ` ${error.message}`;
    }
    Notification('error', errorMessage);
    this.setState({ submit: false });
  }
};

额外提醒

你之前的代码里还漏了给await PopUpAdsService.create()的返回值赋值给response,这会导致后面用response时出现未定义的问题,上面的代码已经帮你修正了这个小疏漏~

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

火山引擎 最新活动