8个我在每次代码审查中看到的 JavaScript 错误(以及如何修复它们)

发布: (2026年3月29日 GMT+8 05:51)
5 分钟阅读
原文: Dev.to

Source: Dev.to

在审查了数百个 PR 后,这些模式不断出现。让我们一次性彻底解决它们。

1. 使用 == 而不是 ===

// 🚫 Wrong – type coercion is unpredictable
if (user.age == "18") ...
if (count == null) ...
if (0 == false) ...   // true!
if ("" == false) ...  // true!

// ✅ Correct – strict equality, no surprises
if (user.age === 18) ...
if (count === null || count === undefined) ...
// Or better:
if (count == null) ...  // Only acceptable for null/undefined check

例外: == null 在检查 null undefined 时是可以接受的。

2. 变更函数参数

// 🚫 Wrong – mutates the caller's object
function addTimestamp(user) {
  user.createdAt = new Date();
  return user;
}

const admin = { name: 'Alice', role: 'admin' };
const timestamped = addTimestamp(admin);
console.log(admin.createdAt); // Oops! admin was mutated too
// ✅ Correct – return a new object
function addTimestamp(user) {
  return { ...user, createdAt: new Date() };
}

3. 未处理异步错误

// 🚫 Wrong – crashes the whole app on network error
async function fetchUser(id) {
  const response = await fetch(`/api/users/${id}`);
  return response.json();
}
// ✅ Correct – handle errors where they happen
async function fetchUser(id) {
  try {
    const response = await fetch(`/api/users/${id}`);
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return { data: await response.json(), error: null };
  } catch (err) {
    return { data: null, error: err.message };
  }
}

const { data, error } = await fetchUser(42);
if (error) { /* handle */ }

4. 在循环中创建函数

// 🚫 Wrong – creates N closures, all referencing the same `i`
const handlers = [];
for (var i = 0; i < 5; i++) {
  handlers.push(() => console.log(i));
}
handlers.forEach(h => h()); // 5 5 5 5 5 — not what you want!
// ✅ Correct option 1 – use `let` (block scoping)
const handlersLet = [];
for (let i = 0; i < 5; i++) {
  handlersLet.push(() => console.log(i));
}
handlersLet.forEach(h => h()); // 0 1 2 3 4 ✓
// ✅ Correct option 2 – just use `map`
const handlersMap = [0, 1, 2, 3, 4].map(i => () => console.log(i));
handlersMap.forEach(h => h()); // 0 1 2 3 4

5. 忘记清理副作用

// 🚫 Wrong – memory leak and stale state
function SearchComponent() {
  const [results, setResults] = useState([]);

  useEffect(() => {
    // If component unmounts before fetch completes, setState on unmounted component
    fetchSearch(query).then(data => setResults(data));
  }, [query]);
}
// ✅ Correct – clean up with `AbortController`
function SearchComponent() {
  const [results, setResults] = useState([]);

  useEffect(() => {
    const controller = new AbortController();

    fetchSearch(query, { signal: controller.signal })
      .then(data => setResults(data))
      .catch(err => {
        if (err.name !== 'AbortError') console.error(err);
      });

    return () => controller.abort(); // Cleanup!
  }, [query]);
}

6. 不使用提前返回

// 🚫 错误 – 深度嵌套,难以阅读
function processOrder(order) {
  if (order) {
    if (order.items.length > 0) {
      if (order.user.isVerified) {
        if (order.total > 0) {
          return submitOrder(order);
        }
      }
    }
  }
  return null;
}
// ✅ 正确 – 扁平、可读,每个失败都明确
function processOrder(order) {
  if (!order) return null;
  if (order.items.length === 0) return null;
  if (!order.user.isVerified) return null;
  if (order.total <= 0) return null;
  return submitOrder(order);
}

7. 使用合适的数组方法

// 🚫 Also wrong – mixing concerns
const results = [];
users.forEach(user => {
  if (user.active) {
    results.push({ ...user, displayName: user.name.trim() });
  }
});
// ✅ Correct – use the right method
const doubled = [1, 2, 3].map(n => n * 2);

const results = users
  .filter(user => user.active)
  .map(user => ({ ...user, displayName: user.name.trim() }));

8. 未正确使用环境检查

// 🚫 Wrong – exposes sensitive info, breaks across environments
const API_URL = "https://api.production.com"; // Hardcoded!
const DEBUG = true; // Always enabled!

// 🚫 Also wrong – string comparison with typo risk
if (process.env.NODE_ENV == "producton") { /* ... */ } // Typo!
// ✅ Correct – centralized config (config.js)
export const config = {
  apiUrl: process.env.REACT_APP_API_URL || 'http://localhost:3000',
  isDev: process.env.NODE_ENV === 'development',
  isProd: process.env.NODE_ENV === 'production',
};

// Use everywhere
if (config.isDev) console.log('Debug info:', data);

快速参考

反模式解决方案
== 宽松相等=== 严格相等
修改参数展开:{ ...obj }
未处理的异步错误try/catch + 错误状态
var 在循环中letmap
useEffect 中没有清理返回清理函数
深层嵌套提前返回
forEach 需要返回结果时map / filter / reduce
硬编码配置环境变量 / 配置文件

我漏掉了哪些你经常看到的模式?在评论中告诉我吧!

0 浏览
Back to Blog

相关文章

阅读更多 »

忽视代码可维护性的痛苦

我最近花了好几个小时调试代码库中一个特别棘手的问题,当时我为了赶紧的截止日期而偷工减料。本该是一个简单的修复,却……