未捕获(承诺){电子邮件:"email already exists"}

Uncaught (in promise) {email: "email already exists"}

所以我正在尝试在我的 redux-form (v7.3.0) 输入字段中实现 asyncValidation。如果电子邮件已经存在并且我正在使用 fetch api 调用后端,则后端 returns 上的 check_email 函数为真。 api 调用成功,returns true 或 false 取决于输入的电子邮件,但不是在带有输入字段的表单中显示消息,而是控制台中存在未捕获的错误。

asyncValidate.js 文件

import { BASE_URL } from "../../config/apiConfig";
const asyncValidate = (values, dispatch, props) => {
      let opts = {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'client': localStorage.getItem('client'),
          'uid': localStorage.getItem('uid'),
          'access-token': localStorage.getItem('access-token')
        }
      };
      return fetch(`${BASE_URL}admin/users/check_email?email=${values.email}`, opts)
        .then((res) => {
          if(!res.ok){
            throw { email: "Something went wrong. Please Type Email again!" }
          }
          else{
            res.json().then((jsonRes) => {

              if (jsonRes) {
                throw { email: "Email already taken!" }; 
              }
            });
          }
        })
        .catch(error => {
          throw error
        });
    };

    export default asyncValidate;

docs 所示,演示验证有效,当验证失败时,错误消息会显示在输入字段中,但上面给出的验证会在控制台中抛出未捕获的错误。

问题出在 else 块中的 then 方法。 throw 语句在 2 个 promise 中,而 redux-form 期望它在一个 promise 中。所以我将其更改为 async/await 语法。 最终代码如下所示。

import { BASE_URL } from "../../config/apiConfig";

const asyncValidate = (values, dispatch, props) => {
  let opts = {
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'client': localStorage.getItem('client'),
      'uid': localStorage.getItem('uid'),
      'access-token': localStorage.getItem('access-token')
    }
  };
  return fetch(`${BASE_URL}admin/users/check_email?email=${values.email}`, opts)
    .then(async (res) => {
      if(!res.ok){
        throw { email: "Something went wrong. Please Type Email again!" }
      }
      else{
        const jsonRes = await res.json();
        if(jsonRes) {
          throw { email: "Email already taken!" };
        }    
      }
    });
};

export default asyncValidate;