JavaScript 进阶营让前端飞程序员

10个最常见的JavaScript错误[译]

2018-02-09  本文已影响166人  ITgecko

前言

这里是10大JavaScript错误:
image.png

1. Uncaught TypeError: Cannot read property

class Quiz extends Component {
  componentWillMount() {
    axios.get('/thedata').then(res => {
      this.setState({items: res.data});
    });
  }

  render() {
    return (
      <ul>
        {this.state.items.map(item =>
          <li key={item.id}>{item.name}</li>
        )}
      </ul>
    );
  }
}
  1. 一个组件的state(比如上面的this.state)在组件生命周期开始时是未声明的,为undefined。
  2. 当你异步获取数据时,组件在获取到数据之前,无论你获取数据的代码是写在constructor方法,还是componentWillMount或者componentDidMount的生命周期里,至少都会调用一次render方法渲染模板。上面的示例代码运行第一次render的时候,this.state.items为undefined。这意味着本该是ItemList的值,却为undefined,接着你就会在console里看到一个错误”Uncaught TypeError: Cannot read property ‘map’ of undefined“
class Quiz extends Component {
  // 在这里添加:
  constructor(props) {
    super(props);

    // 声明state本身,并给他的属性都设置上一个默认值
    this.state = {
      items: []
    };
  }

  componentWillMount() {
    axios.get('/thedata').then(res => {
      this.setState({items: res.data});
    });
  }

  render() {
    return (
      <ul>
        {this.state.items.map(item =>
          <li key={item.id}>{item.name}</li>
        )}
      </ul>
    );
  }
}

2.TypeError: ‘undefined’ is not an object (evaluating

3. TypeError: null is not an object (evaluating

<script>
  function init() {
    var myButton = document.getElementById("myButton");
    var myTextfield = document.getElementById("myTextfield");
    myButton.onclick = function() {
      var userName = myTextfield.value;
    }
  }
  document.addEventListener('readystatechange', function() {
    if (document.readyState === "complete") {
      init();
    }
  });
</script>

<form>
  <input type="text" id="myTextfield" placeholder="Type your name" />
  <input type="button" id="myButton" value="Go" />
</form>

译者注:

4. (unknown): Script error

1. 在header里添加 Access-Control-Allow-Origin 字段
Header add Access-Control-Allow-Origin "*"

Nginx:

location ~ ^/assets/ {
    add_header Access-Control-Allow-Origin *;
}

HAProxy:

rspadd Access-Control-Allow-Origin:\ *
2. 在JavaScript标签上设置crossorigin="anonymous"

5. TypeError: Object doesn’t support property

this.isAwesome();
Rollbar.isAwesome();

6. TypeError: ‘undefined’ is not a function

function testFunction() {
  this.clearLocalStorage();
  this.timer = setTimeout(function() {
    this.clearBoard();    // 这个this指向谁?
  }, 0);
};
function testFunction () {
  this.clearLocalStorage();
  var self = this;   // 把this赋值给self,这个作用域就会被保存下来
  this.timer = setTimeout(function(){
    self.clearBoard();  
  }, 0);
};
function testFunction () {
  this.clearLocalStorage();
  this.timer = setTimeout(this.reset.bind(this), 0);  // bind to 'this'
};

function testFunction(){
    this.clearBoard();    //back in the context of the right 'this'!
};

7. Uncaught RangeError: Maximum call stack

var a = new Array(4294967295);  //OK
var b = new Array(-1); //range error

var num = 2.555555;
document.writeln(num.toExponential(4));  //OK
document.writeln(num.toExponential(-2)); //range error!

num = 2.9999;
document.writeln(num.toFixed(2));   //OK
document.writeln(num.toFixed(25));  //range error!

num = 2.3456;
document.writeln(num.toPrecision(1));   //OK
document.writeln(num.toPrecision(22));  //range error!

译者注:

8. TypeError: Cannot read property ‘length’

var testArray= ["Test"];

function testFunction(testArray) {
    for (var i = 0; i < testArray.length; i++) {
      console.log(testArray[i]);
    }
}

testFunction();
var testArray = ["Test"];

/* Precondition: defined testArray outside of a function */
function testFunction(/* No params */) {
    for (var i = 0; i < testArray.length; i++) {
      console.log(testArray[i]);
    }
}

testFunction();
var testArray = ["Test"];

function testFunction(testArray) {
   for (var i = 0; i < testArray.length; i++) {
      console.log(testArray[i]);
    }
}

testFunction(testArray);

9. Uncaught TypeError: Cannot set property

10. ReferenceError: event is not defined

上一篇下一篇

猜你喜欢

热点阅读