【问题标题】:IntelliJ shows this.props is undefined while console.log suggests otherwiseIntelliJ 显示 this.props 是未定义的,而 console.log 则表明不是这样
【发布时间】:2018-06-18 22:29:07
【问题描述】:

我有一个基于 Material-ui 的对话框,使用 React 和 mobx 编写,我对 mobx+react 很陌生,并试图了解这里的生命周期。

组件看起来像这样:

@observer
export default class AddDialog extends React.Component {

    constructor(store, props) {
        super(props);
        this.store = store;
    }

    handleClose = () => {
        this.props.store.setOpen(false);
    }

    handleDateChange = (e, date) => {
        this.props.store.setDate(date);
    }

    handleTitleChange = (e, title) => {
        this.props.store.setTitle(title);
    }

    render() {
        const actions = [
            <FlatButton
                label="Ok"
                primary={true}
                keyboardFocused={true}
                onClick={this.handleClose}
            />,
        ];

        return (
            <div>
                <Dialog
                    title="Title"
                    actions={actions}
                    modal={false}
                    open={this.props.store.open}
                    onRequestClose={this.handleClose}
                >
                    <TextField hintText="title?" onChange={this.handleTitleChange}/>
                    <DatePicker hintText="Due date" onChange={this.handleDateChange}/>
                </Dialog>
            </div>
        );
    }
}

App.js 中,我的代码如下所示:

@observer
class App extends PureComponent {
    render() {
        return (
            <MuiThemeProvider>
                <FloatingActionButton onClick={this.handleOpenAddPromissDialog}>
                    <ContentAdd />
                </FloatingActionButton>
                <AddPromissDialog store={this.props.addPromissStore} open={false}/>
            </MuiThemeProvider>
        );
    }
}

当我调试代码时,看起来传递给构造函数的 storeprops 参数都使用 render 函数中传递的值进行了初始化。 但是当handleClose 被调用时,this.propsthis.store 都是未定义的。我无法理解我在这里缺少什么。

编辑: 我尝试将变量打印到控制台,它们并没有像我预期的那样显示为未定义但已填充。所以它看起来像和 IntelliJ 问题。

这就是我正在使用的调试配置:

【问题讨论】:

  • 只是通过基本场景/问题运行:您的项目是否定义为静态 Web 项目?您是否运行npm install 来获取所有依赖项?也许通过他们的帮助中概述的检查,看看是否缺少某些东西:jetbrains.com/help/idea/…
  • @NirWeber 不确定链接的问题是否相关。那似乎是 Chrome 问题 - OP 正在询问有关 intelliJ(或 webstorm)属性及其使用 reactjs 的自动解析能力...

标签: javascript reactjs intellij-idea webstorm mobx


【解决方案1】:

问题是由 Babel 在箭头函数中转译this 的方式引起的:转译代码中改为_this,并且没有提供名称映射:

在 Chrome 开发工具(使用与 WebStorm 相同的 API 进行调试)中调试时,您将面临同样的问题:

查看Value of "this" is incorrect when debugging Babel transpiled React with Chrome Devtools 和类似报告

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-27
    • 2020-04-22
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2020-03-22
    • 2017-11-10
    相关资源
    最近更新 更多