React中使用Yup条件验证遇‘expected 1 argument’错误的解决办法
解决Yup when条件验证的"expected 1 argument"错误
你的问题出在.when()配置中then和otherwise的写法不符合Yup的API规范,同时可以优化部分逻辑:
错误原因
Yup的.when()方法中,then和otherwise字段应该接收当前schema作为参数的函数,或者直接是一个schema实例,但你直接重新创建了Yup.string(),导致语法不匹配,触发"expected 1 argument"错误。
修正后的代码
email: Yup.string() .label('Email professionnel') .when('validateEmailExist', { // 单个依赖项可直接写字段名,无需数组 is: true, then: (schema) => schema.test( 'emailexists', 'Email déjà utilisé !', async (value) => { if (!value) return true; // 空值直接通过,后续可由required验证 try { const response = await axios.get<boolean>(`/api/resources/existEmail/${companyId}/${value}`); return !response.data; // 接口返回true表示已存在,验证不通过,返回false } catch (error) { return false; // 接口报错时默认验证不通过 } } ), otherwise: (schema) => schema .matches(/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/, 'Le champ "Email professionnel" doit être un email valide.') .required(), }),
关键修改点
- 将
then和otherwise改为接收当前schema的函数,复用已有的string()schema(包含之前的label配置),符合Yup的API要求。 - 简化了test函数的逻辑,直接返回
!response.data,避免冗余的if判断。 - 单个依赖项时,
.when()的第一个参数可以直接写字段名'validateEmailExist',无需用数组包裹(数组写法也支持,但单个字段更简洁)。 - 增加了空值的处理:当value为空时直接返回true,因为
otherwise分支已经包含required()验证,空值会在该分支被拦截。
内容的提问来源于stack exchange,提问作者salim khamadj
相关产品推荐
相关产品推荐

