无法访问同一类中的变量

时间:2017-01-24 11:10:08

标签: javascript reactjs mobx mobx-react

我有一个类似于以下Store类的MobX商店。当我想访问this.user.permits.db时,收到this.user未定义的错误。我想知道为什么我无法访问@observable user

  

src/ui/store/store.js档案:

import { action, observable } from 'mobx'

import { useStrict } from 'mobx';
useStrict(true);

class Store {
    constructor(){
        //
    }
    @observable user

    @action setUser=(user)=>{
        this.user=user
    }

    @observable menus=[
        {menu1: 'DATABASE',
        /*menu2s: ['PC', 'NETWORK', 'TEL', 'PTT'],*/ //-> this line works fine
        menu2s: this.user.permits.db, //-> this line gives an error: Cannot read property 'permits' of undefined
        }
    ]
}

export default new Store
  从src/ui/ui.js导入商店的

store.js文件:

import React from 'react'
import ReactDOM from 'react-dom'

import Layout from './components/layout.js'

import Store from './store/store.js'

//user comes from HTTP GET request
Store.setUser(user)

ReactDOM.render(<Layout store={Store}/>,document.getElementById('ui'))
  

src/views/profile.ejs文件,将user传递给JavaScript:

<!DOCTYPE html>
<html lang='en'>

<head>
    <title>User profile</title>
    <link href="/css/style.css" rel="stylesheet" type="text/css">
</head>

<!--
Pass variables from http GET to JavaScript
also block script injection attacks
ref: https://stackoverflow.com/a/16098699/7312233 
-->
<script>
    function htmlDecode(input){
        var e=document.createElement('div');
        e.innerHTML=input;
        return e.childNodes.length===0?"":e.childNodes[0].nodeValue;
    }
    var user=JSON.parse(htmlDecode("<%= JSON.stringify(user) %>"));
</script>

<div id="ui"></div>

<script src="/js/ui.bundle.js"></script>

</html>
  

CouchDB用户数据库上的示例用户文档上的permits字段定义如下:

enter image description here

更新:

同样this也应该更正。

1 个答案:

答案 0 :(得分:1)

声明类时未设置

this.user,因此this.user.permits会引发错误。你可以这样做:

class Store {
  @observable user
  @observable menus = []
  @action setUser = (user) => {
    this.user = user
    this.menus.push({
      menu1: 'DATABASE',
      menu2s: this.user.permits.db
    })
  }
}