React项目IE11报错:Object不支持'delete'属性或方法(FormData相关)
解决IE11中FormData不支持delete方法的问题
这个问题我太熟悉了——IE11对FormData的API支持一直是个坑,delete()方法恰好是它没实现的功能之一。别担心,我们有几种稳妥的兼容方案可以解决这个问题:
方案1:创建新的FormData并迁移非目标字段
既然不能直接删除,我们可以新建一个FormData对象,把原对象里除了password之外的所有字段都复制过去,再添加新的password值。
如果你清楚原FormData里的所有其他字段(比如file、username这类),可以手动复制:
add() { if (this.state.password.length === 0) { this.props.dispatch(ShowAlert('warning','Please enter password',false,false)) return; } const oldFormData = this.props.fileToSend; const newFormData = new FormData(); // 复制原FormData中的其他字段(示例以file为例) const file = oldFormData.get('file'); if (file) { newFormData.append('file', file); } // 如果还有其他字段,按同样方式复制,比如username、email等 // 添加新的password newFormData.append('password', this.state.password); console.log(newFormData); this.props.dispatch(SendFile(newFormData)); // this.props.close(); }
方案2:利用表单重新生成FormData(如果原数据来自表单)
如果你的fileToSend是从某个表单生成的,那可以直接修改表单中password输入框的值,再重新创建FormData,这样就不需要处理删除逻辑了:
首先给表单和密码输入框添加ref:
// 在组件中定义ref constructor(props) { super(props); this.formRef = React.createRef(); this.passwordInputRef = React.createRef(); } // 渲染时绑定ref render() { return ( <form ref={this.formRef}> {/* 其他表单字段 */} <input type="password" ref={this.passwordInputRef} /> </form> ) }
然后修改add方法:
add() { if (this.state.password.length === 0) { this.props.dispatch(ShowAlert('warning','Please enter password',false,false)) return; } // 先把输入框的值更新为最新的password this.passwordInputRef.current.value = this.state.password; // 重新从表单生成FormData const newFormData = new FormData(this.formRef.current); console.log(newFormData); this.props.dispatch(SendFile(newFormData)); // this.props.close(); }
这个方案的好处是不需要手动复制所有字段,适合表单字段较多的场景,而且完全兼容IE11。
为什么IE11会报错?
IE11的FormData实现遵循的是早期的API规范,没有包含delete()、entries()、getAll()这些较新的方法,所以直接调用delete()就会抛出“Object doesn't support property or method 'delete'”的错误。
内容的提问来源于stack exchange,提问作者egorchik
相关产品推荐
相关产品推荐

