SyntaxError: "use strict" not allowed in function with non-simple parameters
Ngoại lệ JavaScript ""use strict" not allowed in function" xảy ra khi một chỉ thị "use strict" được sử dụng ở đầu một hàm có tham số mặc định, tham số rest, hoặc tham số destructuring.
Thông báo
SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list (V8-based) SyntaxError: "use strict" not allowed in function with default parameter (Firefox) SyntaxError: "use strict" not allowed in function with rest parameter (Firefox) SyntaxError: "use strict" not allowed in function with destructuring parameter (Firefox) SyntaxError: 'use strict' directive not allowed inside a function with a non-simple parameter list. (Safari)
Loại lỗi
Điều gì đã xảy ra?
Một chỉ thị "use strict" được viết ở đầu một hàm có một trong các tham số sau:
Một chỉ thị "use strict" không được phép ở đầu các hàm như vậy theo đặc tả ECMAScript.
Ví dụ
>Câu lệnh hàm
Trong trường hợp này, hàm sum có các tham số mặc định a=1 và b=2:
function sum(a = 1, b = 2) {
// SyntaxError: "use strict" not allowed in function with default parameter
"use strict";
return a + b;
}
Nếu hàm nên ở trong chế độ strict, và toàn bộ script hoặc hàm bao ngoài cũng có thể ở trong chế độ strict, bạn có thể di chuyển chỉ thị "use strict" ra ngoài hàm:
"use strict";
function sum(a = 1, b = 2) {
return a + b;
}
Biểu thức hàm
Một biểu thức hàm có thể sử dụng cách giải quyết khác:
const sum = function sum([a, b]) {
// SyntaxError: "use strict" not allowed in function with destructuring parameter
"use strict";
return a + b;
};
Điều này có thể được chuyển đổi thành biểu thức sau:
const sum = (function () {
"use strict";
return function sum([a, b]) {
return a + b;
};
})();
Hàm mũi tên
Nếu một hàm mũi tên cần truy cập biến this, bạn có thể sử dụng hàm mũi tên như là hàm bao ngoài:
const callback = (...args) => {
// SyntaxError: "use strict" not allowed in function with rest parameter
"use strict";
return this.run(args);
};
Điều này có thể được chuyển đổi thành biểu thức sau:
const callback = (() => {
"use strict";
return (...args) => this.run(args);
})();