在此循环中未修改变量 - 来自 ESLint 的 no-unmodified-loop-condition

Variable is not modified in this loop - no-unmodified-loop-condition from ESLint

我有一个项目,其中 ESLint 从 while 循环中抛出这个错误。这对我来说没有意义。错误说:

497:14 error 'from' is not modified in this loop no-unmodified-loop-condition

497:22 error 'to' is not modified in this loop no-unmodified-loop-condition

这是代码(看while循环):

mediaSettings: (state) => {
    const timestamps = [];
    const events = [];

    state.media.forEach( medium => {
        if( !medium.settings.dates ) return;

        medium.settings.dates.forEach( dateRange => {
            if( !dateRange.date_from || !dateRange.date_to ) return;

            const from = new Date( dateRange.date_from );
            const to = new Date( dateRange.date_to );

            while ( from <= to ) {
                if( timestamps.includes(from.getTime()) ) {
                    from.setDate( from.getDate() + 1 );
                    continue;
                }

                events.push({
                    date: new Date( from.getTime() ),  // Need Date clone via new Date().
                    mediumId: medium.id,
                });
                from.setDate( from.getDate() + 1 );
            };
        });
    });
    return events;
}

那是什么?有人可以告诉我如何解决吗?它没有意义。这不是错误。

我在 this page 上找到了聪明的解决方案,它禁用了某些代码块的 ESLint 以及特定的 ESLint 规则。看起来像:

    mediaSettings: (state) => {
        const timestamps = [];
        const events = [];

        state.media.forEach( medium => {
            if( !medium.settings.dates ) return;
            medium.settings.dates.forEach( dateRange => {
                if( !dateRange.date_from || !dateRange.date_to ) return;

                const from = new Date( dateRange.date_from );
                const to = new Date( dateRange.date_to );
                /* eslint-disable no-unmodified-loop-condition */
                while ( from <= to ) {
                    if( timestamps.includes(from.getTime()) ) {
                        from.setDate( from.getDate() + 1 );
                        continue;
                    }

                    events.push({
                        date: new Date( from.getTime() ),  // Need Date clone via new Date().
                        mediumId: medium.id,
                    });
                    from.setDate( from.getDate() + 1 );
                };
                /* eslint-enable no-unmodified-loop-condition */
            });
        });
        return events;
    } 

如果您使用如下可重新分配的变量,则不会出现此错误:

...
let from = new Date(dateRange.date_from)
let to = new Date(dateRange.date_to)

while (from <= to) {
  if (timestamps.includes(from.getTime())) {
    from = from.setDate(from.getDate() + 1)
    continue
  }

  events.push({
    date: new Date(from.getTime()), // Need Date clone via new Date().
    mediumId: medium.id,
  })
  from = from.setDate(from.getDate() + 1)
}
...