Yoane Wissa’s winner in the final seconds gave Brentford a dramatic victory.
The Bees, now seventh in the Premier League table, took the lead through Bryan Mbeumo’s first-half goal.
Jarrod Bowen equalised with 10 minutes remaining, but Wissa won it by blasting home the loose ball after keeper Lucasz Fabianski had punched away Pontus Jansson’s header.
In a frenetic start, Mbeumo shot against the post and headed narrowly wide before opening the scoring.
Ivan Toney played a key part in the goal, sending Sergi Canos in with a superb through-ball.
Canos was denied by West Ham keeper Fabianski, who was just unable to prevent Mbeumo’s follow-up creeping over the line.
The visitors were put under sustained pressure in the second half and Bowen missed a great chance to equalise when he headed Vladimir Coufal’s cross wide of the target.
Coufal and former Brentford star Said Benrahma also had chances for the Hammers before Bowen atoned for his earlier miss by hauling his team level with a half-volley after Declan Rice had flicked on Aaron Cresswell’s corner.
Brentford: Raya, Jorgensen, Jansson, Pinnock, Canós Baptiste (Jensen 29), Nørgaard, Onyeka (Bidstrup 82), Henry, Mbeumo (Wissa 82), Toney.