React类组件已绑定方法this,FileReader回调内setState不生效求助
报错根因解析
你遇到的this.setState is not a function和构造函数中给Handleimage绑定this的操作无直接关联,核心问题是嵌套在FileReader逻辑里的load事件回调存在this上下文丢失:
- 构造函数的bind操作,仅会让
Handleimage方法本身的顶层作用域指向Register类的组件实例,这个this指向不会自动传递给函数内部定义的独立事件回调 - FileReader的load回调是浏览器事件调度的普通函数,默认上下文既不继承Handleimage的this,更不会自动指向React组件实例,在这个回调里直接写
this.setState时,this要么指向全局对象,要么是undefined,自然找不到类组件实例上的setState方法
可落地的解决方案
- 优先调整load回调的写法,用箭头函数替代普通函数作为onload的处理逻辑:箭头函数没有自身的this绑定,会直接继承外层Handleimage方法的上下文(也就是已绑定的组件实例this),示例代码:
Handleimage(e) { const uploadFile = e.target.files[0] const fileReader = new FileReader() // 用箭头函数作为load回调,替代传统的function 写法 fileReader.onload = (loadEvent) => { this.setState({ profilePic: loadEvent.target.result }) } fileReader.readAsDataURL(uploadFile) } - 兼容旧场景的写法:如果因项目规范不能使用箭头函数,可在Handleimage方法顶层提前缓存组件实例的this引用,在load回调里使用缓存的变量访问状态更新方法:
Handleimage(e) { // 提前缓存组件实例的this const registerInstance = this const uploadFile = e.target.files[0] const fileReader = new FileReader() fileReader.onload = function(loadEvent) { registerInstance.setState({ profilePic: loadEvent.target.result }) } fileReader.readAsDataURL(uploadFile) }
额外排查要点
- 核对构造函数里的bind写法是否正确,常见的低级错误包括bind方法没有传入组件this参数、把bind的结果写错属性名,都会导致绑定失效
- 检查file输入框的onChange绑定:不要写成
onChange={this.Handleimage()}这种渲染阶段直接调用方法的形式,正确写法是传方法引用onChange={this.Handleimage},否则会在组件渲染时就执行逻辑,直接丢失上下文
内容的提问来源于stack exchange,提问作者Juan Ignacio Fernandez
相关产品推荐
相关产品推荐

