The Reds fell behind at the London Stadium after a Said Benrahma shot deflected into the net via Raphael Varane, before Cristiano Ronaldo hauled as level.
Jesse Lingard, who spent a spell with the Hammers on loan last season, then came off the bench to fire home a delightful winner in the 89th minute.
With the game looking won, the hosts were awarded a controversial penalty in the dying seconds, which David De Gea turned away to deny Mark Noble, who was introduced to take the spot-kick. The Irons skipper had successfully converted his last 10 Premier League spot-kicks.