升级WebStorm 2018.1后React Native中this.setState触发ESLint权限警告
解决WebStorm 2018.1中React Native调用this.setState的“Protected member is not accessible”警告
我之前碰到过不少升级WebStorm后出现这类类型检查警告的情况,结合你的环境配置(Node 9.5.0、ESLint 4.19.1),给你几个针对性的解决思路:
1. 修复React类型定义,让WebStorm正确识别setState
WebStorm 2018.1强化了JavaScript/TypeScript的类型推断,很可能是因为React组件的类型定义缺失或未正确加载,导致它把setState误判为受保护成员。
- 先确认项目里是否安装了React和React Native的类型定义包,没有的话执行:
npm install @types/react @types/react-native --save-dev - 然后打开WebStorm的
Settings > Languages & Frameworks > JavaScript > Libraries,检查@types/react和@types/react-native是否已经被添加到项目的库中,如果没显示,点击Download按钮手动添加。
2. 调整WebStorm的检查规则(快速临时解决)
如果暂时不想折腾类型定义,可以直接关闭这个误报的检查:
- 进入
Settings > Editor > Inspections > JavaScript and TypeScript > General > Protected member access - 把这个检查的级别从
Warning改成None,点击Apply保存即可。不过这只是临时方案,还是推荐优先修复类型定义。
3. 优化ESLint配置,确保兼容WebStorm
WebStorm 2018.1和ESLint 4.x可能存在一些兼容性细节问题,调整ESLint配置可以帮助IDE正确识别React组件:
- 先确保安装了ESLint的React插件:
npm install eslint-plugin-react --save-dev - 然后在项目根目录的
.eslintrc(或.eslintrc.json)中添加以下配置:{ "extends": ["eslint:recommended", "plugin:react/recommended"], "plugins": ["react"], "settings": { "react": { "version": "detect" } }, "rules": { // 按需调整规则,比如不需要prop-types检查的话可以关闭 "react/prop-types": "off" } }
4. 调整组件写法,减少类型推断混淆
试试用类属性+箭头函数的写法,这种写法不仅更简洁,还能帮助WebStorm更准确地识别组件的成员:
import React, { Component } from 'react'; class Foo extends Component { // 直接用类属性定义state state = { hello: 'world' }; // 箭头函数自动绑定this,避免构造函数绑定的繁琐 updateSomeState = (newString) => { this.setState({ hello: newString }); }; render() { return <SomeMagicButton onPress={(newString) => this.updateSomeState(newString)} />; } }
5. 清理WebStorm缓存
有时候IDE的旧缓存会导致奇怪的误报,试试:
- 点击
File > Invalidate Caches / Restart - 选择
Invalidate and Restart,重启后再检查警告是否消失。
内容的提问来源于stack exchange,提问作者VDog
相关产品推荐
相关产品推荐

